nginx: redirect everything from http to https, except one url-pattern

You may use map and simple redirect rules, for example:

map $uri $redirect_https {
    /l/page-with-unsafe-iframe         0;
    /l/other-page-with-unsafe-iframe   0; # you can use regex here
    default                            1;
}

server {
    listen 443;

    if ($redirect_https = 0) {
       return 301 http://$server_name$request_uri;
    }

    # other code
}
server {
    listen 80;

    if ($redirect_https = 1) {
       return 301 https://$server_name$request_uri;
    }

    # other code
}

I should mention that 301 redirect is a good practice unlike permanent rewrite.


If the iframe pages are always in the same directory, simple prefix locations could be used.

server {
    listen 443;

    location /l/ {  # redirect https iframe requests to http server
        return 301 http://$server_name$request_uri;
    }
    # ...
}

server {
    listen 80;

    location / {  # the default location redirects to https
        return 301 https://$server_name$request_uri;
    }

    location /l/ {}  # do not redirect requests for iframe location
    # ...
}

Tags:

Nginx