我最近从 apache 切换到 nginx。我的应用程序位于 /var/www/html 下,具有以下结构:
# tree -a /var/www/html
/var/www/html
├── .htaccess
├── folder1
│ ├── .htaccess
│ └── index.php
├── folder2
│ ├── .htaccess
│ └── index.php
├── index.php
├── file1.php
└── file2.php
所有目录中的 .htaccess 文件都相同:
# cat /var/www/html/.htaccess
AddDefaultCharset UTF-8
Options +FollowSymLinks
Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(assets)/ - [L,NE]
RewriteRule ^/?$ index.php?param1=main [QSA,L]
RewriteRule ^([-a-zA-Z0-9_]+)/$ index.php?param1=$1 [QSA,L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/$ index.php?param1=$1¶m2=$2 [QSA,L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/$ index.php?param1=$1¶m2=$2¶m3=$3 [QSA,L]
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/$ index.php?param1=$1¶m2=$2¶m3=$3¶m4=$4 [QSA,L]
RewriteRule ^file1.xml$ file1.php [L]
RewriteRule ^file2.xml$ file2.php [L]
ErrorDocument 400 /error/400/
ErrorDocument 401 /error/401/
ErrorDocument 403 /error/403/
ErrorDocument 404 /error/404/
ErrorDocument 500 /error/500/
RedirectMatch (.*)\.inc /error/404/
RedirectMatch (.*)\.tpl /error/404/
现在我正在尝试构建 nginx 配置。我的目标是进行以下重写:
example.com or example.com/ -> example.com/index.php?param1=main
example.com/anything or example.com/anything/ -> example.com/index.php?param1=anything
example.com/anything/else or example.com/anything/else/ -> example.com/index.php?param1=anything¶m2=else
etc...
文件夹 1 和文件夹 2 也是如此
example.com/folder1 or example.com/folder1/ -> example.com/folder1/index.php?param1=main
example.com/folder1/anything or example.com/folder1/anything/ -> example.com/folder1/index.php?param1=anything
etc...
Nginx 配置目前看起来像:
server {
listen 443 ssl;
server_name example.com;
charset utf-8;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
root /var/www/html;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
我使用了在线转换器并放置了规则,location / {但这不起作用。像 example.com/anything 这样的网址显示 404 和 example.com/anything/ 尝试下载文件