Nginx Redirect to HTTPS with Competing Location Regex

nginxredirect

I have the following configuration inside a nginx server {...} block:

location /someapp { 
  if ( $https != "on" ) { 
    return 301 https://$server_name$request_uri;
  } 

  location ~ \.php$ { 
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php-fpm.sock;
  } 
} 

The problem is:

  • when I access http://example.com/someapp/somefile.html (or just /someapp), I'm am redirected to HTTPS,
  • but when I access http://example.com/someapp/somefile.php, I am not redirected to HTTPS.

By the way, this is consistent with the doc, that says:

To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

So when location ~ \.php$ is a match, location /someapp is ignored, even if the request is for .../someapp/somefile.php.

Having the location ~ \.php$ {...} block outside of the parent location /someapp {...} block doesn't change this behaviour.

How can I redirect every HTTP to HTTPS request to /someapp without having to duplicate the if and return lines into the php location block?

Best Answer

My Suggestion would be

server {
       
        server_name example.com *.example.com;
        listen 80;
        listen [::]:80;
        return 301 https://$host$request_uri;
}

this would create a basic server for port 80 and tell the browser to permanently use 443