skip to Main Content

I am trying to modify URLs and redirect traffic to a new URL without a trailing slash.
Below is my current server block:

    server {
        listen              443 ssl;
        server_name         www.example.com;
        ssl_certificate     /path/to/certificate.crt;
        ssl_certificate_key /path/to/private/key.pem;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;

        # redirects manually entered here: 
        location /long-url-1/ { return 301 https://example.com/short-url-1; }
        location /long-url-2/ { return 301 https://example.com/short-url-2; }

        # all other traffic should be redirected by the rule below:
        location / { return 301 https://example.com$request_uri; }
}

I want to modify the following location block:

    # all other traffic should be redirected by the rule below:
    location / { return 301 https://example.com$request_uri; }

so if the user enters:

https://www.example.com/unknown-url-1/ => (www + with slash) the rule should redirect to:  https://example.com/unknown-url-1 (non-www + no trailing slash)

Or if the user enters:

https://www.example.com/unknown-url-2 => (www + no slash) the rule should redirect to:  https://example.com/unknown-url-2 (non-www + no trailing slash)

I think there are two ways of doing it:

  1. By implementing two location blocks, one for Url requests with slash and one for all URLs without the slash, e.g:
    location / { rewrite ^/(.*)/?$ https://example.com/$1 permanent;}
    location ~* /(.*)/$ { return 301 https://example.com/$1;}
  1. By adding a rewrite inside my existing location block and modifying the $request_uri somehow, eg:
location / { 
 rewrite ^/(.*)/$ /$1 break;
 return 301 https://example.com$request_uri; 
}

Obviously, the above snippets don’t work and I would appreciate your help.

2

Answers


  1. You need to use rewrite to remove the trailing /. But in your example, the first capture is too greedy. Use *? for the lazy quantifier.

    For example:

    location / { 
        rewrite ^(/.*?)/?$ https://example.com$1 permanent;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search