Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nginx

I have a website which should only be reachable over HTTPS except one URL-pattern (because I have on some pages http-iframe's and I would like to avoid security warnings)

E.g. this pages should be redirected to https: http://example.com http://example.com/a/this-is-an-article http://example.com/v/this-is-a-video  This pages should not be redirected to https (or should be redirected form https to http) http://example.com/l/page-with-unsafe-iframe http://example.com/l/other-page-with-unsafe-iframe 
like image 654
tiefenb Avatar asked Jan 09 '15 09:01

tiefenb


People also ask

How do you redirect all HTTP traffic to https within Nginx?

Redirect HTTP to HTTPS version for Specified domain in Nginx Server_name domain-name.com www.domain-name.com – it specifies the domain names. So, replace it with your website domain name that you want to redirect. Return 301 https://domain-name.com$request_uri – it moves the traffic to the HTTPS version of the site.

How do I force Nginx to https?

To set up an HTTPS server, in your nginx. conf file include the ssl parameter to the listen directive in the server block, then specify the locations of the server certificate and private key files: server { listen 443 ssl; server_name www.example.com; ssl_certificate www. example.com.


2 Answers

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     # ... } 
like image 85
Cole Tierney Avatar answered Oct 12 '22 23:10

Cole Tierney


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.

like image 43
Dmitriy Z Avatar answered Oct 12 '22 23:10

Dmitriy Z