In Nginx, how can I rewrite all http requests to https while maintaining sub-domain?

Better Stack Team
Updated on November 23, 2023

To rewrite all HTTP requests to HTTPS in Nginx while maintaining the sub-domain, you can use the rewrite directive in your Nginx server block configuration. Here's an example of how to do this:

  1. Open your Nginx configuration file. This file is usually located in /etc/nginx/nginx.conf or /etc/nginx/sites-available/your-site.
  2. Find the server block that you want to configure for HTTPS redirection. It should look something like this:

     
    server {
        listen 80;
        server_name example.com www.example.com;
    
        # ...other configuration...
    }
    
  3. Inside the server block, add a location block to handle HTTP requests and rewrite them to HTTPS. Here's an example:

     
    server {
        listen 80;
        server_name example.com www.example.com;
    
        # Redirect HTTP to HTTPS
        location / {
            return 301 https://$host$request_uri;
        }
    
        # ...other configuration...
    }
    

    In this example, we're using the return 301 directive to send a permanent (301) redirect response, which instructs the browser to use HTTPS for the requested URL.

  4. Save the configuration file and exit.

  5. Test the Nginx configuration to ensure there are no syntax errors:

     
    sudo nginx -t
    
  6. If the configuration test is successful, reload Nginx to apply the changes:

     
    sudo systemctl reload nginx
    

    With this configuration, all HTTP requests to your server will be redirected to their HTTPS counterparts while maintaining the sub-domain. For example, if a user accesses http://subdomain.example.com, they will be automatically redirected to https://subdomain.example.com.