Score:0

Make nginx redirect to HTTPS even with competing location regex

cn flag

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?

us flag
Please add the complete nginx configuration to the question as shown by `nginx -T` command.
cn flag
@TeroKilkanen I cannot add so much information for confidentiality purposes. I added some nginx doc snippet however, which makes the nature of my problem more clear I hope.
djdomi avatar
za flag
totor, have you maybe thought about replacing the real domain or ips with example.com?
us flag
Without the larger context it is not possible to propose a good solution to the issue.
Score:3
za flag

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

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.