重写CSS路径

时间:2013-04-01 07:04:53

标签: apache .htaccess mod-rewrite

我看了很多,但找不到任何真正解释的东西。我之前使用过htaccess重写没有太多问题,但我似乎无法找到这个失败的地方。我认为它与初始(原始)URL有关,但我似乎无法找到合适的组合。

HTML:

<link rel="stylesheet" type="text/css" href="http://localhost/site/vnd/style/main.css?p=desktop">

htaccess的:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^style/([A-Z]+\.css)\?p=(.*)$ style/$2/$1 [R=301,L]

预期重定向(文件实际存在的位置):

style/desktop/main.css

在正则表达式测试人员中,它分裂并重新创建它很好,但我看不到Apache看到的内容,因此很难调试。我尝试过绝对路径和相对路径的组合,尾随和无尾斜线等等。

在控制台中,正在输出404,告诉我重定向根本不起作用,并且仍在查找原始URL。头:

Request URL: http://localhost/Patterns/mvc/style/main.css?p=desktop
Request Method: GET
Status Code: 404 Not Found

1 个答案:

答案 0 :(得分:1)

RewriteRule无法获取查询字符串。您需要使用条件来捕获它,并相应地传递它:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^p=(.*)
RewriteRule ^style/([a-z]+)\.css$ style/%1/$1.css [R=301,L,NC]

请注意,我已将p密钥移至QUERY_STRING条件,并且我已将NC标志添加到规则中(这意味着它将忽略该情况字符串)。