【问题标题】:Nginx rewrite "directory" language to query stringNginx 重写“目录”语言来查询字符串
【发布时间】:2018-04-14 00:48:09
【问题描述】:

我正在尝试让 Nginx 将假目录重写为要用作语言的查询字符串。例如:

/fr/example.php

在 URL 中应该看起来像这样,但应该重写为

/example.php?language=fr

这是我在 Nginx 配置中尝试过的代码:

rewrite "^(/(fr|en))?/(.*).php$" /$3.php?language=$2 last;

当我访问 example.php 时,我得到了正确的页面,但是当我访问 /fr/example.php 时,我得到了 404 错误。

编辑:这似乎与它是.php 扩展这一事实有关。如果我尝试改用 .html,它会起作用。但不幸的是,我需要它是 php。这是我的nginx.conf 的更多内容,可能会有所帮助,比我上面发布的代码稍晚一点:

location / {
    root   /var/www/example.com;
    index  index.php index.html index.htm;

    rewrite "^(/(fr|en))?/(.*).php$" /$3.php?language=$2 last;
}

error_page 404 /404.php;
location /404.php {
    root /var/www/example.com;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;

    # CUSTOM
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 256 16k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;
    # END CUSTOM

    # With php7.0-fpm:
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

【问题讨论】:

  • 它对我有用。 rewrite...last 包含在哪个块中?
  • 它被location / {包围,就在我添加的fastcgit块之前。
  • 这就是问题所在。处理.php URI 时需要在上下文中,即server 上下文或location ~ \.php$。如果你把它放在location ~ \.php$ - 请改用rewrite...break
  • 我想我不太明白:我只是尝试将它移到 location ~ \.php$ 块中,我的服务器显示错误 500。编辑:我发布的整个配置都在 @987654337 内@块。
  • location 块内使用rewrite...break

标签: nginx url-rewriting


【解决方案1】:

rewrite 语句需要在处理以 .php 结尾的 URI 的上下文中,这意味着 server 块或 location ~ \.php$ 块。

rewrite 放在server 块中的缺点是nginx 测试每个URI 的正则表达式,而不仅仅是以.php 结尾的那些。

当在同一 location 块中处理重写的 URI 时,rewrite 语句应使用 break 后缀。详情请见this document

例如:

location ~ \.php$ {
    rewrite ^(/(fr|en))?/(.*)$ /$3?language=$2 break;
    ...
}

您的正则表达式当前匹配每个 URI(带或不带语言前缀)。如果这不是必需的,请从正则表达式中删除 ?。例如:

rewrite ^/(fr|en)/(.*)$ /$2?language=$1 break;

【讨论】:

  • 太棒了!也非常感谢您提供更详细的信息,这真的很有帮助。
猜你喜欢
  • 2023-03-04
  • 1970-01-01
  • 2010-12-07
  • 2012-10-18
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多