检查了论坛但找不到理想的答案。我最近在我的网站上安装了SSL证书,并且通过.htaccess文件为近400页网址创建了301重定向(让Google保持高兴)。我想过要用;
redirect 301 /contact.php https://www.mydomainname.co.uk/contact.php
但它破坏了网站。我见过的唯一解决方案是
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^contact\.php$ https://www.mydomainname.co.uk/contact.php [L,R=301]
上面似乎有很多代码可用于400页中的每一页!我可以在.htaccess文件中使用更少的代码吗?
非常感谢。希望有人可以提供建议。
答案 0 :(得分:0)
There are two basic ways of redirecting pages with Apache: Redirect
(of mod_alias
) and RewriteRule
etc. (of mod_rewrite
).
Redirect
is very simple: it will just redirect a single URL to another. It can be useful sometimes, but it's usefulness is limited to its simplicity: in the case of HTTP-to-HTTPS redirection, it can't differentiate between HTTP and HTTPS connections, so it will just try to redirect to HTTPS even if you're already on HTTPS (and thus you end up in an infinite redirect loop).
RewriteRule
, on the other hand, is more advanced and flexible. You can use RewriteCond
to conditionally redirect requests; in your case, you'd want to redirect requests only if they're on a HTTP connection.
As you mentioned, you want to redirect to HTTPS for many (I presume all) requests; you can easily do this with only a single rule:
# Enable rewrites
RewriteEngine on
# Only run next RewriteRule on HTTP connections (not HTTPS)
RewriteCond ${HTTPS} off
# Redirect any page to the same URL with https:// schema
RewriteRule (.*) https://${SERVER_NAME}/$1 [L,R=301]
(The ${SERVER_NAME}
variable will automatically be equal to your domain name, so you can even use this on web servers with multiple domain names.)