Correct way to write 301 redirect?

February 22, 2019 256 views
Ubuntu 18.04 Nginx

My question is in regards to the correct way to write a 301 redirect from requests to our old site URLs. When we go live, we need the following redirect:

(.*)mydomain.com/index.php(.*)  —>  https://mydomain.com/home

In other words, any request that starts with: 

should be redirected to https://mydomain.com/home.

My idea for how to do this would be to put the following line in our server block: 

server {
    . . .
    server_name mydomain.com;
    rewrite ^/index.php/(.*)$ https://mydomain.com/home permanent;
    . . .
}

Is this correct? Thanks!

1 Answer

Two or three potential issues I see:

Trailing slash: When you have…

rewrite ^/index.php/(.*)$ https://mydomain.com/home permanent;

nginx is only going to match on URLs like:

Remove the trailing slash to match standard URLs like the ones you listed

rewrite ^/index.php(.*)$ https://mydomain.com/home permanent;

WWW/Non-WWW: if you want one server block to catch WWW/Non-WWW, you have to make sure your server_name block is catching both:

server_name www.mydomain.com mydomain.com;

or to catch all host variants:

server_name _;

HTTP/HTTPS: You may also need to ensure your server block is catching requests on HTTP port (80) and HTTPS (443). You should have listen lines that include ports 80 and 443

listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
listen 443 ssl;
listen [::]:443 ssl;

(they don’t always look exactly like this, for example ipv6only=on; isn’t always there.) The reason there are two lines for each is [::]:80 is matching port 80 in an IPV6 request.

Have another answer? Share your knowledge.