带有重写和 proxy_pass 的 NGINX 子目录

带有重写和 proxy_pass 的 NGINX 子目录

我希望代理能够返回所需的一切,以正确返回http://joelmccune.com通过 NGINX 代理位置查看所需的内容http://nginx/joel。到目前为止,我所拥有的对于站点的根目录来说工作正常,但是当根目录尝试从子目录加载 css 文件等资源时,客户端无法解析它们。

例如,在网站的根目录中,index.html 文件包含一行用于加载外部 css 文件。

<link rel="stylesheet" type="text/css" href="/assets/css/screen.css?v=4a6391e0a5" />

该文件位于...

http://joelmccune.com/assets/css/screen.css?v=4a6391e0a5

...我希望代理能够识别该模式。通过 URL 返回资源...

http://nginx/joel/assets/css/screen.css?v=4a6391e0a5

现在它失败了,出现 404 错误,因为它正尝试从...加载。

http://nginx/assets/css/screen.css?v=4a6391e0a5

显然,有多个子目录,并且我希望能够添加更多代理位置,因此我试图弄清楚如何创建一个通用模式来实现这一点。

这是我正在使用的配置文件...

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    # if the request is a referall from //nginx/joel
    if ($http_referrer ~* nginx/joel) {

        # rewrite the request to be prefixed with //nginx/joel
        rewrite ^/?(.*)$ http://nginx/joel/$2 last;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    # proxy any requests to /joel to http://joelmccune.com
    location /joel {
        proxy_pass http://joelmccune.com/;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

以下是从初始请求到根的响应标头。

HTTP/1.1 200 OK
Server: nginx/1.12.0
Date: Tue, 23 May 2017 20:56:49 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=db5b717394ddd2681553aed3a5a6d354b1495573008; expires=Wed, 23-May-18 20:56:48 GMT; path=/; domain=.joelmccune.com; HttpOnly
Status: 200 OK
x-powered-by: Express
cache-control: public, max-age=0
vary: Accept-Encoding
X-Ghost-Cache-Status: From Cache
CF-RAY: 363aec8a00b479ff-SEA
Content-Encoding: gzip

以下是检索示例 css 资源的请求标头。查看 referer 后,我萌生了尝试使用重写隔离后续资源请求的想法……但这个想法目前行不通。

GET /assets/css/screen.css?v=4a6391e0a5 HTTP/1.1
Host: nginx
Connection: keep-alive
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Accept: text/css,*/*;q=0.1
DNT: 1
Referer: http://nginx/joel/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

下面是我的示例资源、css 文件的响应标头……显然除了确认它没有加载之外没有提供太多见解。

HTTP/1.1 404 Not Found
Server: nginx/1.12.0
Date: Tue, 23 May 2017 20:56:49 GMT
Content-Type: text/html
Content-Length: 571
Connection: keep-alive

提前感谢您提供的任何见解。这几天来,这个问题一直困扰着我。

注意:为了测试并了解这一切是如何工作的,我使用 Vagrant + VirtualBox + Ubuntu + NGINX,并修改了本地 hosts 文件,将所有请求指向http://nginx虚拟机 IP 地址。这应该可以解释上面详述的 URL 结构。

相关内容