【问题标题】:nginx - rewrite js file with php filenginx - 用 php 文件重写 js 文件
【发布时间】:2020-10-07 12:25:37
【问题描述】:

使用 apache 我使用文件 config.php 重写基于域的文件 config.js,config.js 包含由 RewriteRule 指令替换的占位符,这是 .htaccess 文件:

<IfModule mod_rewrite.c>
    RewriteBase /foo
    RewriteEngine On
    RewriteRule config.js config.php [L,QSA]
</IfModule>

当我进入 URL production.com/foo/config.js 我看到一些值,而不是进入 develop.com/foo/config.js 我看到其他值,定义在 config.php 中

现在我需要迁移到 nginx,但我不明白如何复制 apache 规则,我试过了:

location /foo {
  alias /src/www/foo;
  index index.html;
  rewrite config.js config.php break;
  }

但是有内部服务器错误

谢谢

【问题讨论】:

  • 抱歉,我写的是last 而不是break,但没有在配置代码块中更改它。更新了答案。

标签: nginx


【解决方案1】:

所有 nginx URI 都以斜杠开头。使用rewrite config.js config.php,您正在将一个URI 从/foo/config.js 重写为config.php。 nginx 无法处理该 URI,导致内部服务器错误。

rewrite 指令的第一个参数始终被视为点匹配任何符号的正则表达式。因此,您的 rewrite 规则将匹配任何包含 config*js 子字符串的字符串。我不认为这是你真正想要的。

rewrite 指令的第二个参数是一个全新的 URI,而不是字符串的替换部分。要进行替换,请使用 rewrite ^(.*)old-string(.*)$ $1new-string$2 之类的内容。

由于您将请求重写为 PHP 脚本,因此您应该强制 nginx 使用定义 PHP-FPM 处理程序的位置来处理新的 URI。为此,您应该使用last 标志而不是break 一个带有rewrite 指令的标志。

总结所有这些,您需要类似的东西

location /foo {
    alias /src/www/foo;
    index index.html;
    rewrite ^/foo/config\.js$ /foo/config.php last;
}

还有一个注意事项。作为 nginx 文档states:

当位置与指令值的最后一部分匹配时:

location /images/ {
    alias /data/w3/images/;
}

最好使用 root 指令:

location /images/ {
    root /data/w3;
}

因此,如果 foo 子字符串确实相等,则最好在此 location 块中使用 root /src/www; 而不是 alias /src/www/foo;

【讨论】:

  • 感谢回复,这样当我转到example,com/foo/config.js 时,我看到了config.php 文件
  • @hellb0y77 所以你还没有设置 nginx 来使用 PHP-FPM(或任何其他 PHP 处理程序)吗?您应该在您的服务器上安装 php-fpm 并定义一个特殊的 location ~ \.php$ { ... } 来使用它(这是最常见的方法,还有其他选择,例如 NGINX Unit)。默认 nginx 配置应该有一个使用 PHP-FPM 的示例(默认注释)。这超出了您的问题范围,请查看this 一个。
  • nginx 与 php-fpm 一起工作,我尝试将 phpinfo 文件放在 config.php 的同一路径并工作。
  • @hellb0y77 你有rewrite ... last;,而不是rewrite ... break;吗?也许您的浏览器缓存了响应?
  • 是的rewrite ^/foo/config.js$ /foo/config.php last;
猜你喜欢
  • 2013-01-12
  • 1970-01-01
  • 2014-10-11
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 2020-04-06
相关资源
最近更新 更多