使用 .htaccess 将所有子域重定向到主域 (SSL),并将子域作为查询参数

问题描述 投票:0回答:1

尝试以最优雅的方式在

.htaccess
文件中执行以下所有操作:

  • 将所有非 SSL 重定向到 SSL
  • 将 www 重定向到非 www
  • 使用查询字符串参数将所有其他子域重定向到主域 子域。忽略 URL 中的任何其他信息(302 重定向)。例如:
    http(s)://subdomain.example.com(/or/any/other/folder/or_file.html)
    ->
    https://example.com/results.php?q=subdomain
  • 仅使用查询字符串将所有主域 404 重定向到主域 第一个文件夹或文件名作为参数。例如:
    http(s)://example.com/does/not/exist/file.html
    ->
    https://example.com/results.php?q=does

这是我目前所拥有的,除了子域重定向和 SSL 重定向并不总是适用于非 SSL URL 之外,一切正常。不确定事物的顺序,或者是否有办法将其中的一些结合起来。

Options -Indexes
RewriteEngine On
# this rewrites all non-SSL www to main domain (SSL)
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

#redirect all 404 to query string
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/? /results.php?q=$1 [R=302,L,NC]

重要提示:一切都需要重定向而不是重写。

apache .htaccess redirect mod-rewrite subdomain
1个回答
0
投票

并且 SSL 重定向并不总是适用于非 SSL URL。

因为您没有特定的非 SSL (HTTP) 到 SSL (HTTPS) 重定向,只有 www 到非 www 重定向也重定向到 HTTPS。

你可以这样做:

Options -Indexes

RewriteEngine On

# Redirect all 404 (for www or main domain) to query string + main domain
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+) https://%1/results.php?q=$1 [R=302,L]

# Redirect www to main domain (+ HTTPS)
RewriteCond %{HTTP_HOST} ^www\.(.+?)\.?$ [NC]
RewriteRule (.*) https://%1/$1 [R=301,L]

# Redirect subdomains to main domain and query string
RewriteCond %{HTTP_HOST} ^([^.]+)\.(example\.com)
RewriteRule ^ https://%2/results.php?q=%1 [R=302,L]

# Redirect HTTP to HTTPS (remaining URLs) - must already be at main domain
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

我已经安排/构建了规则,以尽量减少可能的重定向次数。最多只有 1 个重定向。

从 HTTP 到 HTTPS 的重定向(最后一条规则),我们在其中针对

HTTPS
服务器变量进行测试,假设 SSL 证书安装在您的应用程序服务器上并且您有一个相对标准的实现。

您可以使规则完全通用并消除对

example.com
(确定什么是子域等)的依赖,方法是假设域始终采用
<domain>.<tld>
的形式(例如,或者可能是 TLD 的已知子集)。

只是一个观察……您将两个子域和不存在的文件/目录的第一个路径段重定向到相同的 URL 格式似乎有点奇怪?

© www.soinside.com 2019 - 2024. All rights reserved.