简体   繁体   中英

301 Redirect from http to https same page name

checked the Forum but could not find an ideal answer. I have recently installed a SSL Certificate on my site and in the process of creating 301 redirects via the .htaccess file for nearly 400 page urls (to keep Google happy). I thought of using;

redirect 301 /contact.php https://www.mydomainname.co.uk/contact.php

but it breaks the site. The only solution I have seen is;

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^contact\.php$ https://www.mydomainname.co.uk/contact.php [L,R=301]

The above seems a lot of code to use for each of the 400 pages! is there a quicker way with less code I can use in the .htaccess file?

Many thanks. Hope someone can advise.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM