单击锚链接时,Nginx - Localhost端口丢失

时间:2018-05-08 14:46:38

标签: docker nginx

我使用Docker在macOS上运行nginx以在http://localhost:8080上提供静态文件。

单击锚链接时,端口正在丢失。

例如,点击<a href="/foo">会链接到http://localhost/foo而不是http://localhost:8080/foo

我的nginx配置是:

server {
  listen               80 default_server;

  server_name          _;

  root                 /var/www/root;
  index                index.html index.php;

  location ~ /\. {
    deny all;
  }

  location ~* /(?:uploads|files)/.*\.php$ {
    deny all;
  }

  error_page 404 /404.html;

  location / {
    try_files $uri $uri/ $uri.html =404;
  }

  location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass php:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
  }
}

/var/www/root的目录结构是:

├── foo
│   └── index.html
├── bar
│   └── index.html
└── baz
    └── index.html

但是,在更改时:

try_files $uri $uri/ $uri.html =404;

为:

try_files $uri/index.html $uri $uri/ $uri.html =404;

锚链接正确链接。

但是,以下情况不起作用:

try_files $uri/ $uri $uri.html =404;

到底发生了什么?有没有办法从$uri/index.html中排除try_files并让锚点链接保留端口?

更新

这有效,但我不太清楚为什么。

if (-d $request_filename) {
  rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}

location / {
  try_files $uri $uri/ $uri.html =404;
}

1 个答案:

答案 0 :(得分:1)

我无法看到Dockerfile,但我假设你运行的端口映射为8080:80的容器。但是,nginx可能仍然使用端口80发送Host头,并且锚标签使用该主机给出了如何计算基URI:

  

用户代理必须根据以下优先级(最高优先级到最低优先级)计算基URI:

     
      
  1. 基本URI由BASE元素设置。
  2.   
  3. 基本URI由协议交互期间发现的元数据提供,例如HTTP标头(参见[RFC2616])。
  4.   
  5. 默认情况下,基URI是当前文档的URI。并非所有HTML文档都具有基URI(例如,有效的HTML文档可能出现在电子邮件中,并且可能不是由URI指定的)。如果这些HTML文档包含相对URI并依赖于默认的基本URI,则会被视为错误。
  6.   

参考:https://www.w3.org/TR/html401/struct/links.html#edef-BASE

对于开发,听起来像运行8080:8080的容器应该可行。对于生产,您可能希望通过envvar设置适当的server_name或主机头。