将Apache中的FQDN重写为主机名

huangapple go评论47阅读模式
英文:

mod_rewrite apache FQDN to Hostname

问题

我正在尝试找到一个mod_rewrite代码,用于强制将访问完全限定域名(FQDN)的用户重写为不带域名的主机名,而且不希望他们陷入循环中。我只能找到相反方向的重写示例。有人有建议吗?

例如,如果我访问http://appname.example.com/test.php

重写后的URL应该是http://appname/test.php

任何建议都将很好。

英文:

I'm trying to find a mod_rewrite code for forcing users that go to FQDN to be re-written to the hostname without the domain and don't want them to be stuck in a loop. I can only find re-write examples for the other way round. Anyone have a suggestion on how I can do this?

So example if I was to go to http://appname.example.com/test.php

The rewritten URL should be http://appname/test.php

Any suggestions would be great.

答案1

得分: 0

http://<appname>.example.com/<url-path> 重定向到 http://<appname>/<url-path>(其中 <appname><url-path> 完全可变,<appname> 也是本地网络上可解析的主机名),你可以在根目录的 .htaccess 文件顶部使用 mod_rewrite 做以下操作:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?!www\.)([a-z-]+)\.example\.com [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=302,L]

这个规则使用负向先行断言来排除 www 子域名。

%1替换 字符串中是从请求的 主机名 中捕获的 <appname> 的反向引用。

%{REQUEST_URI} 包含完整的相对根路径 URL 路径(以斜杠开头)。

这也处理以点结尾的完全限定域名(FQDN)。

英文:

To "redirect" http://<appname>.example.com/<url-path> to http://<appname>/<url-path> (where <appname> and <url-path> are entirely variable and <appname> is also a resolvable hostname on the local network) then you would do something like the following using mod_rewrite at the top of the root .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?!www\.)([a-z-]+)\.example\.com [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=302,L]

This excludes the www subdomain using a negative lookahead.

%1 in the substitution string is a backreference to the <appname> as captured from the requested hostname.

%{REQUEST_URI} contains the full root-relative URL-path (starting with a slash).

This also handles FQDN (that end in a dot).

huangapple
  • 本文由 发表于 2023年2月8日 23:27:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定