简体   繁体   中英

htaccess Redirect problem with internal pages

When I type http://mywebsite.com my server redirects successfully to http://www.mywebsite.com but when I type http://mywebsite.com/page.php it redirects to http://www.mywebsite.com not to http://www.mywebsite.com/page.php .

My server is Apache, I use these lines to redirect from non-www to www in my .htaccess

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

Thanks

Try it like this:

# Redirect non-www to www
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Or to redirect ot HTTPS:

# HTTP OVER SSL
  RewriteCond %{HTTPS} !on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

I would suggest the following:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^mywebsite\.com [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R=301,L]

I think your condition was being too strict. You were ending it ( $ ) too soon.

I'd rather use this if you want to add a www at the start of your url if none exists :

RewriteEngine On
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301]

I do not recommend redirecting users to the in the .htaccess. You should do that in the config file for the virtual host if possible, using a temporary redirect, or permanent if appropriate, for visitors coming from a non http port (eg 80).

It might look something like this:

<VirtualHost *:80>
   ServerName mywebsite.com
   ServerAlias www.mywebsite.com
   DocumentRoot "/var/www/mywebsite.com"
   Redirect / https://www.mywebsite.com/
</VirtualHost>

<VirtualHost *:443>
   ServerName mywebsite.com
   DocumentRoot "/var/www/mywebsite.com"
   Redirect / https://www.mywebsite.com/
   ... SSL stuff
   .... your https config for mywebsite here, with SSLCertificate, I believe you need a separate one for without www, to redirect to www.
</VirtualHost>

<VirtualHost *:443>
   ServerName www.mywebsite.com
   DocumentRoot "/var/www/mywebsite.com"
   SSL STUFF****
</VirtualHost>

Then in the .htaccess you should not need any rewriting at all.

I believe the problem with the other answers, is that you were rewriting the location for a file, when it should be in the format of %{DOCUMENT_ROOT}%{REQUEST_URI}, so you might have an error handler sending you back to the home page. So check your error logs and access logs.

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