How to allow a URL through HTTP and redirect the rest to HTTPS

Shailender Choudhary
Modern-SysAdmin
Published in
2 min readOct 4, 2017

Sometimes we want to allow a specific URL through HTTP and redirect the rest to HTTPS. This might be a API or any other custom URL.

Without much ado, let’s get our hands dirty with Nginx. First we will allow the URL through HTTP and Redirect the rest to HTTPS. You will Need to add the following to your Nginx virtual host file [ /etc/nginx/sites-enables/default]

set $allow_http 'no' ;

if ($uri ~* "^\/(internal|export)\/") {
set $allow_http 'yes' ;
}

if ($request_uri = '/some_url_here') {
set $allow_http 'yes' ;
}

if ($allow_http = 'no') {
return 301 https://$host$request_uri ;
}
# HTTP Server Block
server
{
listen 80;
# So here comes the tricky part to allow handling some urls
# both via http / https:

set $allow_http 'no' ;

if ($uri ~* "^\/(internal|export)\/") {
set $allow_http 'yes' ;
}

if ($request_uri = 'some_url_here') {
set $allow_http 'yes' ;
}

if ($allow_http = 'no') {
return 301 https://$host$request_uri ;
}

# Tricky Part Ends Here
access_log /var/log/nginx/access.log;

location / {

proxy_set_header X-Forwarded-Host $host;
# proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_pass http://127.0.0.1:8080/;
proxy_read_timeout 90;
}

}
#HTTPS Server Block
server
{

listen 443;
#Allow the changes over https as well
# Tricky URL changes

set $allow_https 'yes' ;

if ($uri ~* "^\/(internal|export)\/") {
set $allow_https 'yes' ;
}

if ($request_uri = 'some_url_here') {
set $allow_https 'yes' ;
}
#End changes
client_max_body_size 200M;
ssl_certificate /etc/ssl/certs/snake-oil.crt;
ssl_certificate_key /etc/ssl/private/snake-oil.key;

ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;

access_log /var/log/nginx/access.log;

location / {

proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

proxy_pass http://127.0.0.1:8080/;
proxy_read_timeout 90;
}
}

Now lets check the conf file for errors

nginx -t

And restart the nginx service with

service nginx restart

If you face any issues, please let me know in comments.

--

--