Networking HowTos
Networking HowTos

Rewrite a http request to https with nginx

July 12, 2012 Linux

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.

You Might Also Like

  • Krzysztof July 29, 2012 at 3:11 am

    Thank you verry much. This art is verry userfull and save my time.