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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github