Nginx configuration files are divided into several blocks, common from the outside in order of “HTTP”, “server”, “location”, etc. The default inheritance relationship is from the outside in, that is, the inner block automatically gets the value of the outer block as the default value.

“Index”instruction

The “index” directive should be defined in “server”. By inheritance, the “index” directive will work in all “locations”.

The “if” command

A lot of people like to do a bunch of checks with the “if” command, but that’s really what the “try_files” command does:

try_files $uri $uri/ /index.php;Copy the code

On top of that, some people tend to think of the “if” directive as kernel-level, but it’s actually part of the rewrite module, and Nginx configuration is actually declarative rather than procedural, so when mixed with non-rewrite module directives, the results may not be what you want.

Fastcgi_params configuration file

Nginx has two fastCGI configuration files, “fastcgi_params” and “fastcgi.conf”, which are not too different, the only difference being that the latter has one more line of “SCRIPT_FILENAME” definition than the former:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;Copy the code

Note that there is no slash between $document_root and $fastcgi_script_name.

Nginx originally only had “fastcgi_params”, but it turned out that many people were defining “SCRIPT_FILENAME” in a hard-coded way, so “fastcgi.conf” was introduced to standardize usage.

Why introduce a new configuration file instead of modifying the old one? Because the “fastcgi_param” directive is an array, it is the same as a normal directive: the inner layer replaces the outer layer; Unlike normal commands, when used multiple times at the same level, they are added instead of replaced. In other words, if “SCRIPT_FILENAME” was defined twice at the same level, they would both be sent to the back end, which could cause some potential problems, and a new configuration file was introduced to avoid this situation.

There is also a security concern: with “cgi.fix_pathinfo” turned on in PHP, PHP may parse the wrong file type as a PHP file. If Nginx and PHP are installed on the same server, the simplest solution is to do a filter with the “try_files” command:

try_files $uri =404;Copy the code

The following configurations are made based on the previous analysis:

server { listen 80; server_name test.com; root /path; index index.html index.htm index.php; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ /.php$ { try_files $uri =404; include fastcgi.conf; Fastcgi_pass 127.0.0.1:9000; }}Copy the code