我正在将站点从 apache 迁移到 nginx,并坚持使用以下配置。
我有网站 http://example.com/其中显示了主要(英文)版本。 另外,我还有几种语言可以使用相应的子目录打开。 http://example.com/de http://example.com/fr , http://example.com/es或http://example.com/es/ (带有尾部斜杠)。
这些子目录是虚拟的(不存在),但应该从根目录打开相同的页面。 php 脚本处理语言表示。
现在英文网站可以正常工作,但是其他语言则无法工作。 我可以打开http://example.com/es/ (仅带有尾随字符)并且它打开主页,但是无法访问所有其他页面(例如 http://example.com/es/test.html 这是 seo 好友 url)。我已经回顾了很多类似的问题和答案,但没有一个有帮助。 这是我的配置:
server {
....
root /var/www;
index index.php index.html index.htm;
location / {
rewrite ^/(de|fr|it|es)\/(.*)$ /$2;
try_files $uri $uri/ @fallback;
}
location @fallback {
rewrite ^(.*)$ /seo.php?$args last;
}
location ~* \.(jpeg|ico|jpg|gif|png|css|js|pdf|txt|tar|gz|wof|csv|zip|xml|yml) {
access_log off;
try_files $uri @static;
expires 14d;
add_header Access-Control-Allow-Origin *;
add_header Cache-Control public;
root /var/www;
}
location @static {
rewrite ^/(\w+)/(.*)$ /$2 break;
access_log off;
rewrite_log off;
expires 14d;
add_header Cache-Control public;
add_header Access-Control-Allow-Origin *;
root /var/www;
}
location /backend/ {
rewrite ^(.*)$ /backend/index.php last;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
它以前在 apache 上的工作原理如下:
RewriteRule ^(de|fr|it|es)\/(.*)$ $2
RewriteCond %{REQUEST_URI} !^/(backend|template)/
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpeg|png|js|css|swf|php|ico)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ seo.php [L]
最佳答案
显然,Apache 在应用重写之前正在将 /es
转换为 /es/
。除非目录确实存在,否则 nginx
不会执行此操作。
但是,通过调整正则表达式并将尾部斜杠设置为可选,可以轻松解决此问题。
试试这个:
rewrite ^/(?:de|fr|it|es)(?:/(.*))?$ /$1;
(:? )
构造是一个非捕获组。
编辑:
如果您希望“明显”添加尾部斜杠,那么您将需要重定向。例如:
rewrite ^/(de|fr|it|es)$ /$1/ permanent;
rewrite ^/(?:de|fr|it|es)/(.*)$ /$1 last;
关于regex - 配置nginx语言子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785161/