【问题标题】:Convert Apache rewrite rules to Nginx将 Apache 重写规则转换为 Nginx
【发布时间】:2016-06-18 08:51:50
【问题描述】:

如何将这些规则从 .htaccess (apache) 转换为 Nginx conf?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1-$2.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

我使用这些规则来重写请求,例如:

/someurl1/ => someurl.html (/company/ to /company.html
/someurl1/someurl2/ => someurl-someurl2.html (/projects/3/ to /projects-3.html)

我已经尝试过了(不起作用):

if (!-e $request_filename) {
  rewrite ^/([^/]+)/$ /$1.html;
  rewrite ^/([^/]+)/([^/]+)/$ /$1-$2.html;
}

try_files $uri $uri/ =404;

我哪里错了?

【问题讨论】:

    标签: apache .htaccess mod-rewrite nginx rewrite


    【解决方案1】:

    我已经测试了以下,它似乎工作:

    location / {
        try_files $uri $uri/ @rewrite;
    }
    location @rewrite {
        rewrite ^/([^/]+)/$ /$1.html last;
        rewrite ^/([^/]+)/([^/]+)/$ /$1-$2.html last;
        return 404;
    }
    

    RewriteCond %{REQUEST_FILENAME} !-f 测试实际上是由try_files 指令完成的。

    详情请见this

    【讨论】:

    • index.html 怎么样?
    • 默认情况下,nginx 将在出现以 / 结尾的 URI 时执行 index.html 文件。详情请见this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2016-08-09
    • 1970-01-01
    • 2013-01-23
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多