regex - 配置nginx语言子目录

标签 regex apache mod-rewrite nginx url-rewriting

我正在将站点从 apache 迁移到 nginx,并坚持使用以下配置。

我有网站 http://example.com/其中显示了主要(英文)版本。 另外,我还有几种语言可以使用相应的子目录打开。 http://example.com/de http://example.com/fr , http://example.com/eshttp://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/

相关文章:

java - 使用 Java 正则表达式查找多个字符串匹配

regex - 根据正则表达式对文件行进行排序

apache - 安装Apache(libaprutil)时出错

apache - .htaccess 为父级而不是子级重定向?

apache - 如何防止用户通过url访问多个目录下的图片

php - Css、图像和 js 在 .htaccess 文件中不起作用

java - 为什么我的 while(matcher.find()) 进入无限循环?我将它与 Streams 一起使用

regex - 这个 perl 匹配模式有什么问题?

apache - 在 Ubuntu 14.04 'has no installation candidate' 中安装 Apache2 时遇到错误

windows - Apache Web 服务器 - 相当于 Windows 10 的 apxs