首页 > 解决方案 > 将 .htaccess 重写转换为 NGINX 配置

问题描述

我在将两个 RewriteCond 的重写规则“块”转换为 NGINX 配置时遇到了困难,我希望对此有一个全新的看法。我试图转换为 NGINX 的重写规则块如下所示:

# Production
RewriteCond %{HTTP_HOST} ^www\.domain\.nl$ [NC]
RewriteRule ^(_next/.*)$ https://lp.domain.nl/$1 [P]
RewriteRule ^(assets/next/.*)$ https://lp.domain.nl/$1 [P]
RewriteRule ^(lp2/.*)$ https://lp.domain.nl/$1 [P]
RewriteRule ^(advice/welcome)$ https://lp.domain.nl/$1 [P]
RewriteRule ^(RewriteRule ^(api/.*)$ https://lp.domain.nl/$1 [P]
RewriteRule ^api/v1/(.*)$ https://app.domain.nl/api/v1/$1 [P]

标签: .htaccessnginxurl-rewriting

解决方案


我建议使用地图捕获 https 重定向路径。在地图中使用正则表达式可以最大限度地减少它们对配置流程的影响。

map $uri $redirect_https {
    ~^/(?<path>_next/.*) lp.domain.nl/$path;
    ~^/(?<path>assets/next/.*) lp.domain.nl/$path;
    ~^/(?<path>lp2/.*) lp.domain.nl/$path;
    ~^/(?<path>api/v1/.*)$ app.domain.nl/$path;

    # default api check should come last
    ~^/(?<path>api/.*) lp.domain.nl/$path;
}

server {
    server_name www.domain.nl;
    listen 80;

    location = /advice/welcome {
        return 301 https://lp.domain.nl/advice/welcome;
    }

    if ($redirect_https) {
        return 301 https://$redirect_https;
    }

    # ... other non-https config here
}

推荐阅读