How to Create NGINX Redirects

NGINX Redirects on NGINX Web Server

NGINX can be used as a web server (in lieu of Apache) or proxy server. For those using it as a web server, creating NGINX redirects requires editing server configuration files. This is different from Apache which also checks .htaccess files during web server requests. NGINX doesn’t use .htaccess. Need to know how to redirect HTTP to HTTPS in NGINX? Don’t worry. It’s a simple process, as easy as hiding your NGINX server version. Below we’ll cover how to:

If you don’t need cPanel, don't pay for it. Only pay for what you need with our Cloud VPS solutions

check markCentOS, Debian, or Ubuntu    check markNo bloatware    check markSSH Key management made easy

Create NGINX Redirects

SSH into your NGINX web server as user root. Edit your NGINX configuration file using Nano, Vim, Emacs, etc. We’ll be editing domain configuration files in the sites-enabled directory as it is the easiest method to create NGINX redirects. The file may state default or take the name of the domain.

nano /etc/nginx/sites-enabled/default
vim /etc/nginx/sites-enabled/

Ignoring the comment lines, the default file will resemble the code block 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;

Most changes below can all be done within existing code. Just remember to restart NGINX after making changes for them to take effect.

systemctl restart nginx

To save time troubleshooting, negate caching issues by testing changes in a private browsing session.

Redirect HTTP to HTTPS

To force encrypted connections, add the following to a new line under server_name _;:

return 301 https://$host$request_uri;

You can install a free domain-validated SSL certificate with Certbot.

Redirect to Force www

Deciding to explicitly use “www” or not for your website improves search engine optimization (SEO). First, add the following above the existing server { line:

server {
        listen       80;

If you want to force HTTPS, add this line above the closing } bracket:

return 301$request_uri;

Finally, add the following to a new line under server_name _;:

return 301$request_uri;

Redirect a Domain to Another Domain

This is useful when migrating your website to a newer domain or subdomain (e.g. /blog or /forum). Add the following to a new line under server_name _;:

return 301$request_uri;

Permanent Redirect for a Single File

To redirect a single page or file URL, add the following to a new line under server_name _;:

rewrite ^/page1.html$ /page2.html permanent;

Learn more from our Cloud Server Hosting Product Guide.

Jacqueem Technical Writer

Technical writer focused on cybersecurity and musicianship.

More Articles by Jacqueem

Was this article helpful? Let us know!