使用 .htaccess 重写通配符域的 URL

Posted

技术标签:

【中文标题】使用 .htaccess 重写通配符域的 URL【英文标题】:URL rewrite with .htaccess for wildcard domain 【发布时间】:2017-05-09 00:35:19 【问题描述】:

我想用通配符重写网址:

https://any.example.com

收件人:

https://example.com/fixed/any

'any' 是任意字符串,'fixed' 是固定字符串。

谢谢。

【问题讨论】:

感谢您告诉我们这个! 你能显示你的通配符域的VirtualHost 配置吗? 也许可以选择使用自定义路由? 【参考方案1】:

尝试在您的.htaccess 文件中添加一些这样的重写规则:

RewriteEngine on
RewriteBase /

# Make sure it's not an actual file or 
# directory, being accessed. If you wish.
#RewriteCond %REQUEST_FILENAME !-f
#RewriteCond %REQUEST_FILENAME !-d

# Match the subdomain
RewriteCond %HTTP_HOST !^www\.example\.com$
RewriteCond %HTTP_HOST ^(.*)\.example\.com$

# Rewrite the request to the main domain:
# %1: The subdomain matched against HTTP_HOST in the previous RewriteCond.
# $1: The request URI.
RewriteRule ^(.*)$ https://example.com/fixed/%1/$1 [L,R,QSA]

如果这不是最后的重写规则,请随意删除 L 标志。有关这方面的更多信息,请参阅RewriteRule Flags。

你可以test it online。

【讨论】:

以上是关于使用 .htaccess 重写通配符域的 URL的主要内容,如果未能解决你的问题,请参考以下文章

.htaccess 问题、虚拟子域和 Codeigniter

当 wordpress 不在域的根文件夹中时重写它的路径

Apache 重写:如何避免在省略 url 结尾斜杠时显示 url 参数?

用子目录重写url

htaccess 301 重定向新基础域名的通配符

我想用 .htaccess 禁用目录而不是子目录的访问