regex - 将 URL 从 http ://example. com/blog/重写为 http ://blog. example.com/

标签 regex apache .htaccess mod-rewrite

什么 RewriteRule (使用 .htaccess/mod_rewrite )我应该用来重定向 http://example.com/blog/ (带 www 或不带)到 http://blog.example.com/ ?

我正在使用以下内容,但得到一个重定向循环:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/blog/ [L,R=301]

RewriteCond %{HTTP_HOST} www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/blog/ [L,R=301]

最佳答案

在您现有的规则中,您似乎有一些错误的方法,我认为没有必要进行否定(即 ! )测试。

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^/blog/$ http://blog.example.com/ [L,R=301]

但是我建议您不要使用 RewriteCond检查主机名的指令,只需确保规则在正确的 VirtualHost 中为 www.example.com .
<VirtualHost ...>
ServerName www.example.com
ServerAlias example.com

RewriteRule ^/blog/ http://blog.example.com/ [L,R=301]
</VirtualHost>

(注意:假设 blog.example.comwww.example.com 实际上是独立的虚拟主机)

关于regex - 将 URL 从 http ://example. com/blog/重写为 http ://blog. example.com/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/759361/

相关文章:

PHP 除法返回不同的结果 (Linux/Windows)

javascript - 处理部署新设计

php - 在 htaccess 中重写不应用带有 2 个参数的 css

Apache 正在将文件夹重定向到同名的 .html 文件

php - RewriteEngine 不在本地重写 URL?

javascript indexof regex A-Za-z0-9 总是返回 false

java - 仅当负前瞻和负后瞻都满足时才拆分字符串

python - 如何在 python 中返回 re.search() 的字符串表示

regex - Scala:标记简单算术表达式

php - Apache + PHP 中的 "End of script output before headers"