nginx multiple locations for one rule regex

2019-05-29 04:56发布

问题:

I'm trying to force nginx to process through php-fpm following urls:

any url ending with

  • .php
  • /sitemap.xml
  • /api/api.js

I'm trying the following regex, but it does not work:

location ^~ ^((.*\.php)|/sitemap.xml)+$ {

回答1:

Try ...

location ~ (\.php|sitemap\.xml|api/api\.js)$ {
    ...
}


回答2:

You shouldn't really be trying to force Nginx to send things to PHP. That's kind of 'the wrong way'. You should let Nginx see if the file exists and pass if it doesn't. It's understood that *.php needs to be processed by PHP so you pass .php.

location / {
    try_files $uri /index.php;
}

location ~ \.php {
    fastcgi_pass unix:/tmp/php-fpm.socket;
}

location = /api/api.js {
    fastcgi_pass unix:/tmp/php-fpm.socket;
}

location = /sitemap.xml {
    fastcgi_pass unix:/tmp/php-fpm.socket;
}

Trying to maintain a regular expression for locations when you don't understand how Nginx location blocks work is going to be extremely painful in the long run.

http://wiki.nginx.org/HttpCoreModule#location