【问题标题】:Need help translating this htaccess rewrite rule to Nginx需要帮助将此 htaccess 重写规则转换为 Nginx
【发布时间】:2012-07-17 15:56:13
【问题描述】:

嗨——我已经为此苦苦挣扎了好几天。这看起来很简单,但我就是做不到。

我有一个用 CakePHP 开发的网站。有一个响应/css/profiles/g/whatever.css 的脚本(“whatever” 是什么,它实际上是一个传递给动作的参数),它回显生成的 CSS 并将其保存到 /css/profiles/whatever.css。

我在 Apache 中有一条规则,它接受对 /css/profiles/whatever.css 的请求,如果它不存在,则将请求重写为 /css/profiles/g/whatever.css 而不进行重定向,因此客户端永远不会注意到它是由脚本响应的并且文件不存在。

这就是我在 Apache 中所拥有的:

# Profile CSS rules
RewriteCond %{REQUEST_URI} ^/css/profiles/
RewriteCond %{REQUEST_URI} !/css/profiles/g/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^css/profiles/(.*)$ /css/profiles/g/$1 [L]

# CakePHP's default rules
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]

现在我正在使用 Nginx 将网站移动到服务器上,到目前为止我已经得到了这个:

# Profile CSS rules
location ~ ^/css/profiles/(?!g/)(.*)$ {
    if (!-f $request_filename) {
      rewrite ^/css/profiles/(.*)$ /css/profiles/g/$1 last;
      break;
    }

 }

# CakePHP's default rules
location / {

   try_files $uri $uri/ /index.php?$uri&$args; }

条件似乎奏效了,因为如果我转到 /css/profiles/whatever.css 并打印出 PHP 的 $_SERVER 变量,它就会给我

[QUERY_STRING] => /css/profiles/g/whatever.css&

注意&。这意味着它到达了try_files 部分并将$uri 添加到查询字符串中,并且它具有正确的$uri。

但是……

[REQUEST_URI] => /css/profiles/whatever.css

这就是故障。似乎它并没有真正改变 $request_uri,这是 CakePHP 需要控制什么控制器参与什么。

更新:REQUEST_URI 的值是正确的……这里的问题是 Cake 会寻找不同服务器变量的值来决定哪个控制器将响应。按此顺序:$_SERVER['PATH_INFO']、$_SERVER['REQUEST_URI']、$_SERVER['PHP_SELF'] 和 $_SERVER['SCRIPT_NAME'] 的组合,最后是 $_SERVER['HTTP_X_REWRITE_URL']。这就是它失败的原因。

任何帮助将不胜感激。

谢谢。

注意:我昨天发布了this question on Serverfult,因为我认为它更适合那里但没有得到答案,这也是我在这里发布它的原因。

【问题讨论】:

    标签: apache .htaccess cakephp mod-rewrite nginx


    【解决方案1】:

    所以我终于让它工作了:

    location ~ ^/css/profiles/(?!g/)(.*)$ {
      set $new_uri /css/profiles/g/$1;
      if (!-f $request_filename) {
        rewrite ^/css/profiles/(.*)$ /css/profiles/g/$1 last;
      }
    }
    

    ...最后:

    location ~ \.php$ {
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      include fastcgi_params;
    
      ... some other stuff were here related to fastcgi
      fastcgi_param PATH_INFO $new_uri; # <--- I added this
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-29
      • 2012-03-16
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多