Howtos / Articles

Rewrite a http request to https with nginx

If you have a web server running nginx that accepts both http and https connections, there may be times where you want to prevent anyone from accessing a specific page/url using a insecure http connection. For example, login or registration pages. You always want these to be secure if you can.

Add the following into the main “location /” block, located in the http “server” section in your nginx configuration file for your site.

if ($request_uri ~* "/login.php") {
    rewrite ^ https://$host$request_uri permanent;
}

Note: This assumes your HTTP and HTTPS “server” sections/site details seperated in the nginx site configuration file, otherwise it would end up in a loop.

eg:

#HTTP Site Details
server {
    listen 80;
    <...config details removed...>
    location / {
        <...config details removed...>
        if ($request_uri ~* "/login.php") {
            rewrite ^ https://$host$request_uri permanent;
        }
    }
}

#HTTPS Site details
server {
    listen 443;
    ssl on;
    <...config details removed...>
    location / {
        <...config details removed...>
    }  
}

It also assumes your HTTPS connection is using the default https port (port 443). You can change the url to go to a different port using “https://$host:port$request_uri permanent;” and replace port with the port number you are using for https connections.

Restart nginx, and test.

When you go to http://your.web.site/login.php in your web browser, it should now redirect you to https://your.web.server/login.php automatically.



Share this howto article!
  • Facebook
  • Twitter
  • Reddit
  • email

1 comment to Rewrite a http request to https with nginx

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>