Home > Blockchain >  SEO URL and Rewrite Rule force on one domain
SEO URL and Rewrite Rule force on one domain

Time:11-21

I have a rewrite rule to force user to go from example.com to www.example.com. This is for SEO reasons so that I have no duplicated websites and content on my Google results.

 # BEGIN Spark

AddDefaultCharset UTF-8

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$  /$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
</IfModule>

<IfModule mod_deflate.c>
<FilesMatch "\.(html|php|txt|xml|js|css|ttf|otf|ico|json|svg|)$">
SetOutputFilter DEFLATE
</FilesMatch>
</IfModule>
# END Spark

My question. If now people post a link example.com/news they always will redirect to the frontpage like www.example.com. How can I manage that they still can use and post short URLs like example.com/news1 or example.com/news2 and will redirect to www.example.com/news1 or www.example.com/news2 respectively.

CodePudding user response:

You've put the rule in the wrong place. It needs to go before the internal rewrite (to the front-controller: index.php). eg. at the top of the file, not at the end.

By placing it last it will only correctly redirect physical directories (which includes the homepage) and static resources (images, CSS, JS, etc.). All other "short URLs" that are routed through the front-controller will be redirected to index.php and you'll see the "frontpage".

And... to avoid a double redirect when requesting example.com with a URL that contains a trailing slash then include an absolute URL in the trailing slash removal rule and include your non-www to www rule immediately after that.

For example:

RewriteEngine On

# Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$  https://www.example.com/$1 [L,R=301]

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

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

# Front-controller
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

You will need to clear the browser cache before testing since the erroneous 301 (permanent) redirects will have been cached by the browser. (Test with 302 - temporary - redirects to avoid caching issues.)

Aside: An additional concern is that these directives are inside a # BEGIN Spark ... # END Spark code block - which makes it look as if these directives are perhaps maintained by some automated process? In which case, they might be overwritten?

  • Related