Traefik (Docker) 没有设置 X-Forwarded-* Headers?

Traefik (Docker) Not Setting X-Forwarded-* Headers?

我正在尝试 运行 Apache in Docker,在 https 的 Traefik 反向代理后面。一切正常,除了当我访问一个没有尾部斜线的文件夹 URL 时,Apache 将我重定向到 non-https(即 https://www.example.com/folder -> http://www.example.com/folder/). This is caused Apache mod_dir DirectorySlash, as described here & )。解决方案是使用重写规则,该规则在之前启动DirectorySlash,像这样:

# Redirect to HTTPS before Apache mod_dir DirectorySlash redirect to HTTP
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteCond %{LA-U:REQUEST_FILENAME} -d
RewriteRule ^/(.*[^/])$ https://%{HTTP_HOST}// [R=301,L,QSA]

但是,问题是 Traefik 似乎没有设置 X-Forwarded-* headers。这是我得到的 headers 的屏幕截图:

这是我在 Apache docker-compose 文件中使用的标签:

  labels:
    - traefik.enable=true
    - traefik.port=80
    - traefik.frontend.rule=PathPrefix:/web  #Apache is accessible under https://example.com/web/

我试过各种标签组合,但无论我做什么,x-forwarded-* header 似乎总是不见了。例如 (, ref):

- "traefik.frontend.headers.SSLProxyHeaders=X-Forwarded-Proto:https"
- "traefik.frontend.headers.SSLRedirect=true"

我什至尝试让 Traefik 添加我自己的自定义 header,但无法显示它们 (ref):

- "traefik.https.middlewares.testHeader.Headers.CustomRequestHeaders.X-Script-Name=test"

...但是,只是为了说服自己我没有疯 & 这 实际上 运行 落后于 Traefik,& Traefik 可以 添加我可以看到的 headers,这确实有效并导致 X-Frame-Options header 出现在 Firefox 中:

- traefik.frontend.headers.frameDeny=true

所以总而言之,问题是:为什么 Traefik 不设置 x-forwarded-* headers(然后我可以在我的 Apache RewriteRules 中使用它)——我怎样才能得到它要这样做吗?

你试过了吗

traefik.frontend.passHostHeader: true

如果可能的话,我建议让 traefik 对 http 到 https 重定向进行排序:

[entryPoints]
    [entryPoints.http]
    address = ":80"
      [entryPoints.http.redirect]
      entryPoint = "https"

    [entryPoints.https]
    address = ":443"
      [entryPoints.https.tls]

对于发现此问题并想知道的任何人,我的问题是双重的:

1) X-Forwarded-* headers 在浏览器中不可见。您可以使用 phpinfo() 或转储 $_SERVER 变量在服务器上查看它们:

2) 重定向不起作用(修复 DirectorySlash 问题)的原因是除了上面列出的 RewriteRules 之外,您的 htaccess 必须包括 RewriteOptions AllowNoSlash。来自 Apache documentation

By default, mod_rewrite will ignore URLs that map to a directory on disk but lack a trailing slash, in the expectation that the mod_dir module will issue the client with a redirect to the canonical URL with a trailing slash. [...] the AllowNoSlash option can be enabled to ensure that rewrite rules are no longer ignored. This option makes it possible to apply rewrite rules within .htaccess files that match the directory without a trailing slash, if so desired.