简体   繁体   中英

htaccess redirect all url if they have no www prefix to a new url with www prefix

I have this in HTACCESS.

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

This works but if the domain has some directry it doesnt work.

A:    site.com/users/profiles/index.php?id=1

B:    site.com/index.php?id=1

"A" fails to redirect and is returned as it is while "B" is redirected to www.site.com/index.phpid=1

Here is the content of htaccess inside site.com/user/

Options -Indexes +FollowSymLinks
RewriteEngine On
###########music#######
RewriteCond %{THE_REQUEST} \ /+index\.php\?artist=([^&]+)&title=([^&]+)&a=([^&\ ]+)
RewriteRule ^ /audio/%1/%2/%3? [L,R=301]
RewriteCond %{THE_REQUEST} \ /+audio\.php\?artist=([^&]+)&title=([^&\ ]+)
RewriteRule ^ /audio/%1/%2? [L,R=301]
#################internallly redirect////////////
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?artist=$1&title=$2&a=$3 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^audio/([^/]+)/([^/]+)/([^/]+)$ index.php?artist=$1&title=$2&a=$3 [L,QSA]
###############gzip######
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
#ExpiresByType text/css A86400
#ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦swf)$">
Header set Cache-Control "public"
</FilesMatch>
AddType text/cache-manifest appcache

How do I modify this to redirect all?

Since you have .htaccess in /users/ directory also therefore any .htaccess in parent directory is not in effect for a request containing /users/ .

Insert this rule just below RewriteEngine On line in /users/.htaccess :

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

PS: There is way to inherit parent rewrite rules from child .htaccess but those rules are executed after application of current .htaccess , something that might give wrong results since you're also internally rewriting some URIs and changing value of %{REQUEST_URI} .

References:

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