如果子域名前面没有 www,则无法正常工作

如果子域名前面没有 www,则无法正常工作

我之前在 cpanel 中设置了一个子域名(sub.domain.com 重定向到 domain.com/sub/),今天我突然发现它将浏览器中的 URL 重写为 www.domain.com/sub/,而不是直接保留为 sub.domain.com。我不确定问题出在哪里,但决定删除我的子域名并在 cpanel 中重新创建它。现在我只能通过访问 www.sub.domain.com 来访问它(sub.domain.com 会产生服务器未找到错误)。

编辑:问题似乎出在 .htaccess 文件上。删除后,一切恢复正常。但是现在我的新问题是如何正确配置 .htaccess 文件。我最初对其进行了调整,以尝试完成以下操作:

我有三个文件夹,live、staging 和 dev:

1)对 domain.com 或 www.domain.com 的请求被定向到 domain.com/live(并且用户看到的 url 始终被重写为 www.domain.com)。

2)分别请求staging.domain.com 和 dev.domain.com 或指向 domain.com/staging 和 domain.com/dev,用户在浏览器中看到 staging.domain.com 或 dev.domain.com。

3)当我在 cpanel 中添加任何子域名时,浏览器通常不会重写它们。

我当前的 .htaccess 文件很好地完成了第 1 项,但将 staging.domain.com 重写为 www.domain.com/staging 等等。

RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
RewriteRule ^$ /index.html

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/live/
RewriteRule ^(.*)$ /live/$1

答案1

我调整了原始代码的逻辑,似乎找到了可行的解决方案。我所做的每项测试都成功了,如果有人发现代码中存在任何缺陷,或者如何优化代码以适应原始问题中提出的条件,请提出意见。我对重写几乎没有经验。谢谢。

工作代码:

# REDIRECTS
#
# Add www in front of all URLs except subdomains
#
RewriteCond %{HTTP_HOST} ^domain\.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
RewriteRule ^$ /index.html
#
# Add forward slash at end of www URLs
#
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\..+$
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/ [R=301,L]
#
# Forward requests to live folder
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/live/
RewriteRule ^(.*)$ /live/$1

*注:我不确定为什么代码的最后一部分没有将子域 URL 重定向到实时文件夹。它按我想要的方式工作,只是不确定为什么 ^_^;

相关内容