An instance of automatic completion using rewrite in the pseudo static configuration of Nginx
- 2020-05-10 23:28:55
- OfStack
When using nginx+php, you often need to use pseudo-static Settings. Is there a way to make nginx auto-complete paths?
It took a long time to realize such a function in the past two days:
Request/a/b/c
If the file does not exist, find/a/b/index php, / c as PATH_INFO;
If the file does not exist, find /a/ index.php, /b/c as PATH_INFO;
If the file does not exist, find/index.php, /a/b/c as PATH_INFO;
If the file does not exist, return 404.
This loss of performance behavior is not suitable for deployment, but it is still convenient for native debugging :)
The server side should have the following code, with the rest using its own configuration:
index index.php index.html index.htm;
location / {
set $path $request_uri;
set $path_info "";
try_files $uri $uri/ @404;
}
location @404 {
if ($path ~ ^(.*)(/.+)$) {
set $path $1/index.php;
set $path_info $2;
rewrite .* $path last;
}
return 404;
}
location ~ .+.php($|/) {
fastcgi_split_path_info ^(.+.php)(/.+)$;
if ($path_info !~ .*) {
set $path_info $fastcgi_path_info;
}
try_files $fastcgi_script_name @404php;
fastcgi_param PATH_INFO $path_info;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_pass unix:/usr/local/var/run/php-fpm.sock;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
}
location @404php {
if ($path = /index.php) {
return 404;
}
if ($path ~ ^(.*)(/.+)/index.php$) {
set $path_info $2;
set $path $1/index.php;
rewrite .* $path last;
}
return 404;
}
The Rewrite Flags
last - you basically use this Flag.
break - discontinue Rewirte, no longer match
redirect - returns the temporary redirected HTTP status 302
permanent - returns permanently redirected HTTP state 301
Rules:
1. rewrite is generally configured in location of non-root, which is break; It is better to use last for root location, because if you configure fastcgi or proxy to access jsp files, break is not accessible under root location
Pattern matching in the form of regular expressions, such as ~* and ~