NGINX Redirect Rule: Subfolder only to HTTPS?

10,031

Solution 1

Read the four rules in the wiki entry linked by AlexD. Regular expression locations (like your PHP location) take precedence over plain static locations. To prevent that, you want to use the ^~ flag on your static location:

location ^~ /www/admin/ {
    rewrite ^ https://domain.com$request_uri? permanent;
}

EDIT: Also, you shouldn't set your root in location /. Set it in the server and let all your locations inherit the setting. See Pitfalls and Common Mistakes 1.2

Solution 2

Check nginx documentation for description of location directive. You should use location instead location =

Share:
10,031

Related videos on Youtube

Professor Frink
Author by

Professor Frink

Updated on September 18, 2022

Comments

  • Professor Frink
    Professor Frink over 1 year

    I'm trying to redirect anyone who access the admin section of my site to the HTTPS version of it. The current rewrite rule is as follows:

    server {
            listen          80;
            server_name     domain.com;
    
            location / {
                    index index.php index.html;
                    root  /home/domain.com/public;
                    }
    
            #Redirect Admin requests to secure server
            location /www/admin/  {
                    rewrite ^/(.*) https://domain.com$1 permanent;
                    }
    }
    

    The problem with this rule is it is only forwarding http://domain.com/www/admin to HTTPS - going to http://domain.com/www/admin/index.php, for example, does not redirect. Any idea how to correct this so that anything BELOW /www/admin also gets redirected?

  • Professor Frink
    Professor Frink about 13 years
    Tried that already, doesn't help :(
  • AlexD
    AlexD about 13 years
    There is another error in rewrite statement - you seems to be redirecting to domain.comwww/admin (note missing slash).
  • Professor Frink
    Professor Frink about 13 years
    That doesn't seem to be causing any issues - when I go to (http) domain.com/www/admin, it correctly redirects to *(https) domain.com/www/admin - it's just (http) domain.com/www/admin/index.php or similar which doesn't redirect –
  • AlexD
    AlexD about 13 years
    You probably have some other rules using regexps like location ~* *.php$ which has precedence over location /www/admin. See @kolbyjack answer how to fix it.
  • Professor Frink
    Professor Frink about 13 years
    This appears to have been the problem - Thanks for the help!