想将此.htaccess规则转换为nginx

时间:2012-10-01 11:58:46

标签: .htaccess mod-rewrite nginx rewrite

我是nginx的新手,并且真的不知道如何做到这一点。以下代码在htaccess中基本上做的是例如

如果浏览器从此网址请求此css文件

http://www.example.com/folder1/css/style-30493094.css

然后显示此文件

http://www.example.com/folder1/css/style.css

此代码中的所有其他已定义扩展也是如此。 css,js,png,jpg,gif 就像浏览器从这个网址请求这个js文件一样

http://www.example.com/folder1/js/javascript-2938293.js

然后显示此文件

http://www.example.com/folder1/js/javascript.js

其实我正在努力实现这一目标。 http://derek.io/blog/2009/auto-versioning-javascript-and-css-files/

RewriteEngine On
RewriteRule ^folder1/(css|js|images)/([a-z]+)-([0-9]+)\.(css|js|png|jpg|gif)$ /folder1/$1/$2.$4 [L]

1 个答案:

答案 0 :(得分:1)

基于此:http://wiki.nginx.org/HttpRewriteModule#rewrite 看起来您可以使用当前的正则表达式并在nginx.conf中使用它。

rewrite ^folder1/(css|js|images)/([a-z]+)-([0-9]+)\.(css|js|png|jpg|gif)$ /folder1/$1/$2.$4 last;

所以你的整个服务器块可能如下所示:

server {
    listen 192.168.0.1;
    server_name blah.blah.com;

    location ~ \.(css|js|png|jpg|gif) {
        rewrite ^folder1/(css|js|images)/([a-z]+)-([0-9]+)\.(css|js|png|jpg|gif)$ /folder1/$1/$2.$4 last;
    }
}

编辑:你只需要适当调整正则表达式。 在您提供的案例中:

rewrite ^(.*/?)([a-z]+)-([0-9]+)\.(css|js|png|jpg|gif)$ /$1$2.$4 last;

将重写:

[Anything with an optional trailing slash (or nothing)] followed by [at least one alphabetic character (lowercase only)] followed by [a hyphen] followed by [at least one numeric character] followed by [a dot] followed by [one of css|js|png|jpg|gif]

[That first optional text followed by an optional slash][the alphabetic part (i.e. style)].[the final css|js|png|jpg|gif]