Webmasters commonly use the .htaccess rules to implement redirects on websites. However, this form of redirect is not effective while using Nginx.
As a part of our Server Management Services, we help our Customers to implement redirects regularly.
Let us today discuss how to implement redirect using Nginx.
Common Methods for Redirects
The two common methods for redirects are temporary redirects and permanent redirects.
Temporary redirects are useful to serve URLs temporarily from a different location. It is particularly useful while performing maintenance to redirect users to the maintenance page.
However, permanent redirects indicate that the old URL no longer servers the content and the browsers should not attempt to access it anymore. These are particularly useful in situations like change in the domain names.
Redirect URLs using Nginx
In Nginx, the configuration file typically found in the document root directory of the site(s), /etc/nginx/sites-available/directory_name.conf, handles these redirects. Formats for some of the commonly used redirect codes are given below:
Temporary Page to Page Redirect
server {
# Temporary redirect to an individual page
rewrite ^/oldpage$ http://www.domain.com/newpage redirect;
}
Permanent Page to Page Redirect
server {
# Permanent redirect to an individual page
rewrite ^/oldpage$ http://www.domain.com/newpage permanent;
}
Permanent www to non-www Redirect
server {
# Permanent redirect to non-www
server_name www.domain.com;
rewrite ^/(.*)$ http://domain.com/$1 permanent;
}
Redirect to www permanently
server {
# Permanent redirect to www
server_name domain.com;
rewrite ^/(.*)$ http://www.newdomain.com/$1 permanent;
}
Permanent Redirect an old URL to New URL
server {
# Permanent redirect to new URL
server_name olddomain.com;
rewrite ^/(.*)$ http://newdomain.com/$1 permanent;
}
We have added the redirect using the rewrite directive. The ^/(.*)$ regular expression will use everything after the / in the URL. For example, http://olddomain.com/index.html will redirect to http://newdomain.com/index.html.
Redirect HTTP to HTTPS
server {
# Redirect to HTTPS
listen 80;
server_name domain.com www.domain.com;
return 301 https://example.com$request_uri;
}
After placing these rewrite rules, it is a good idea to test the configuration prior to running a restart. Nginx syntax can be checked with the -t flag to ensure there is not a typo present in the file.
nginx -t
If it does not return any result, then the syntax is correct. Thus we can reload Nginx for the redirects to take effect.
systemctl restart nginx
[Need any further assistance to redirect URLs using Nginx? – We’re available 24*7]
Conclusion
In short, Nginx requires the redirect codes to be added to the configuration file. Today, we saw how our Support Engineers implements various redirects using Nginx.
0 Comments