Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx redirect all http to https with exceptions

I would like to redirect all http traffic to https with a handful of exceptions. Anything with /exception/ in the url I would like to keep on http.

Have tried the following suggested by Redirect all http to https in nginx, except one file

but it's not working. The /exception/ urls will be passed from nginx to apache for some php processing in a laravel framework but that shouldn't matter.

Any suggestions for improvement much appreciated!

server {
    listen 127.0.0.1:80;

    location / {
        proxy_pass http://127.0.0.1:7080;
        proxy_set_header Host             $host;
        proxy_set_header X-Real-IP        $remote_addr;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Accel-Internal /internal-nginx-static-location;
        access_log off;
    }

    location /exception/ {
        # empty block do nothing
        # I've also tried adding "break;" here
    }

    return 301 https://localhost$request_uri;
}
like image 735
mba12 Avatar asked Jan 20 '15 18:01

mba12


1 Answers

Nginx finds the longest matching location and processes it first, but your return at the end of the server block was being processed regardless. This will redirect everything but /exception/ which is passed upstream.

server { 
    listen 127.0.0.1:80;
    access_log off;

    location / {
        return 301 https://localhost$request_uri; 
    }

    location /exception/ {
        proxy_pass http://127.0.0.1:7080;
        proxy_set_header Host             $host;
        proxy_set_header X-Real-IP        $remote_addr;
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Accel-Internal /internal-nginx-static-location;
    }    
}
like image 167
Ben Grimm Avatar answered Sep 23 '22 01:09

Ben Grimm