Rumesh Bandara Rumesh Bandara - 3 months ago 20
Apache Configuration Question

Convert Apache RewriteCond to Nginx

I want to convert following Apache config to Nginx compatible config.

What it currently does is redirect all traffic which DOESN'T contain ^/nexus/content* in uri to HTTPS. That means even if I access http:// example.com/nexus only, it should go to HTTPS.

Bottom line is I want keep http:// example.com/nexus/content* in HTTP but http:// example.com/nexus should redirect to HTTPS. Hope the question is clear :)

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/nexus/content*
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


I tried following Nginx configs but didn't work so far. Appreciate any help.

if ($request_uri != ^/nexus/content*) {
rewrite (.*) https://example.com$request_uri;
}


And

location ~ ^/nexus/content* {
}

location / {
rewrite ^(.*)$ https://$http_host$request_uri redirect;
}

Answer

I'm not sure if this will work, but here goes:

server {
       listen         80;
       server_name    example.com;
       if ($request_uri !~ "^/nexus/content*") {
           return     301 https://$server_name$request_uri;
       }
}

server {
       listen         443 ssl;
       server_name    example.com;
       add_header Strict-Transport-Security "max-age=31536000"; # MiTM Mitigation
       // your normal rules here 
}

Similar to yours, but it does a redirect and not a rewrite.

Comments