Nginx:向所有重写添加/注入相同的根路径?

Nginx:向所有重写添加/注入相同的根路径?

我目前在以下路径上托管内容:

http://oldsite/samples/content/
http://oldsite/samples/ql
http://oldsite/samples/api/content/plans/
http://oldsite/samples/api/streams/map.xml
...

我即将推出一个新网站,它最终将提供以下内容:

http://newsite/content/
http://newsite/ql
http://newsite/api/content/plans/
http://newsite/api/streams/map.xml
...

意思是样品子路径将被删除。

因此基本上是反转版本:

Nginx 将一个路径重定向到另一个路径

在此过渡期间,我的计划是改写这些路径使用 nginx。目前我的配置如下:

/etc/nginx.conf.d/sandbox.conf

服务器 {

    #listen 80;
    #listen [::]:80;

    listen 8082 default_server;
    listen [::]:8082 default_server;


    location / {
         proxy_pass http://localhost:8080/;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Forwarded-Port $server_port;
         
         location /content/ {
            rewrite 301 /samples/content/;
         }

         location /ql {
            rewrite 301 /samples/ql;
         }

         location /api/content/plans/ {
            rewrite 301 /samples/api/content/plans/;
         }

         location /api/streams/map.xml {
            rewrite 301 /samples/api/streams/map.xml;
         }
    }

}

但是有没有更干净的方法来做到这一点 - 使用一些正则表达式/通配符模式,这样我就不必写出每个路径?

如果我这样做:

/etc/nginx.conf.d/sandbox.conf

服务器 {

    #listen 80;
    #listen [::]:80;

    listen 8082 default_server;
    listen [::]:8082 default_server;

    location / {
         proxy_pass http://localhost:8080/;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_set_header X-Forwarded-Proto $scheme;
         proxy_set_header X-Forwarded-Port $server_port;
         
         location /samples/content/ {
            rewrite 301 /content/;
         }

         location /samples/ql {
            rewrite 301 /ql;
         }

         location /samples/api/content/plans/ {
            rewrite 301 /api/content/plans/;
         }

         location /samples/api/streams/map.xml {
            rewrite 301 /api/streams/map.xml;
         }
    }

}

我得到:

$ curl localhost:8082/content
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html>

和访问日志:

, request: "GET /content HTTP/1.1", host: "localhost:8082"
2021/03/15 10:05:18 [error] 81448#81448: *4 open() "/usr/share/nginx/html/content" failed (2: No such file or directory), client: 127.0.0.1, server: , request: "GET /content HTTP/1.1", host: "localhost:8082"

绕过 nginx 我得到:

curl localhost:8080/samples/content
Hello!

答案1

下面将从/samples所有重定向的 URL 中删除前缀:

location ~ /samples(.*) {
    return 301 $1;
}

如果您想使用其他域,请使用:

return 301 https://new.example.com$1;

location街区里。

相关内容