This guide explains how to create NGINX redirects.
Follow the steps:
- Log in via SSH as the root user to access your NGINX web server.
- Utilise a text editor such as Nano, Vim, Emacs, or any of your preferences to modify the NGINX configuration file.
- We will make changes to the domain configuration files in the sites-enabled directory, which is the most straightforward way to implement NGINX redirects.
- These files may be named “default” or correspond to the specific domain you wish to configure.
nano /etc/nginx/sites-enabled/default
vim /etc/nginx/sites-enabled/example.com - Excluding the comments, the default file will have a structure similar to the code block provided below-
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
} - Many of the modifications mentioned below can be incorporated into the existing code. Please remember to restart NGINX after implementing these changes to ensure they are applied.
systemctl restart nginx - To save time on troubleshooting, it is a good practice to eliminate caching issues when testing your changes. You can do this by conducting your tests in a private browsing session.
- Redirect HTTP to HTTPS-To enforce encrypted connections, insert the following code on a new line below “server_name;”-
return 301 https://$host$request_uri; - Redirect to Force www-
Opting for either the inclusion or exclusion of “www” in your website’s URL can enhance search engine optimization (SEO). Initially, place the following code above the current “server {” line:
server {listen 80;server_name www.domain.com;}To enforce HTTPS, include this line before the closing } bracket.return 301 https://www.domain.com$request_uri;Lastly, add the following to a new line under server_name _;-return 301 http://www.domain.com$request_uri; - Redirect a domain to another Domain-This is beneficial when transitioning your website to a new domain or subdomain (e.g., /blog or /forum). Insert the following code on a new line under “server_name _;”-return 301 https://newdomain.com$request_uri;
- Permanent Redirect for a Single File-
For redirecting a single page or file URL, place the following code on a new line below “server_name _;”-rewrite ^/page1.html$ /page2.html permanent;
This way you can create NGINX redirects. Hope you liked our article.