301 redirect is very easy to setup if we are using Apache webserver, usually we do it via editing the .htaccess file, however if we switched to Nginx webserver then we will find that the old .htaccess 301 trick doesn’t work here. So, here is how to apply a 301 redirect in Nginx? It is almost as easy as we use it in .htaccess world, let’s start.
Nginx 301 Redirect Solutions
In Nginx there are some types of redirections like www or non www redirection, single page redirection, whole directory redirection and complete domain redirection to another domain. Let’s see all of them.
Redirect Non-www to www Redirect
server {
listen 80;
server_name domain.com;
rewrite ^/(.*)$ http://www.domain.com/$1 permanent;
}
Redirect www to Non-www Redirect
server {
listen 80;
server_name www.domain.com;
rewrite ^/(.*)$ http://domain.com/$1 permanent;
}
Also Read: Nginx Redirection Non-www to www and www to Non-www
Single Page 301 Redirect
Sometimes you will need to redirect an entire page instead of the domain to avoid 404 errors, in this case you can use this code inside server block to redirect a single page.
server {
...
if ( $request_filename ~ oldpage/ ) {
rewrite ^ http://www.domain.com/newpage/? permanent;
...
}
Directory 301 Redirect
Alternatively you may need to rediret an old directory to a new one, in this case you can use this kind of solution, remember to place it inside server block configuration:
server {
...
if ( $request_filename ~ myolddirectory/.+ ) {
rewrite ^(.*) http://www.domain.com/mynewdirectory/$1 permanent;
...
}
Domain to Domain 301 Redirect with Posts
If you are planning to change your domain or changing business name then domain redirection is the only best solution to preserver same users on new domain.
server {
...
server_name domain.com www.domain.com;
rewrite ^ $scheme://www.new-domain.com$request_uri permanent;
...
}
Domain to Domain 301 Redirect
It is same as above but it does not redirect page request to another domain’s page. It is useful when you are planning to redirect a complete website to just your another domain’s home page.
server {
...
server_name domain.com www.domain.com;
rewrite ^ $scheme://www.new-domain.com;
...
}
If you have any other examples to share, feel free to comment below.
Leave a Reply