Htaccess redirect

Hi Matt,

Well, I would NEVER use that code (but for minor reasons). However, your original post stated that you wanted to redirect TO house in order to serve house.html. That is a circular redirection which must be handled very carefully (and the code posted only handled the second redirection).

Further, Apache’s Redirect code:

[quote=https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirect]Redirect Directive
Description:	Sends an external redirect asking the client to fetch a different URL
Syntax:	Redirect [status] URL-path URL
Context:	server config, virtual host, directory, .htaccess
Override:	FileInfo
Status:	Base
Module:	mod_alias[/quote]

So, when you get the syntax wrong, 500 errors is all that you will get from the server. In other words …

Redirect 301 /house.html /house

… would have been syntactically correct but it would have prevented house.html from ever being served.

As stated above …

[quote=http://dk.co.nz/seo#example-10 titled Redirect TO New Format]# assumes usable link is index.php?id=alpha
# and alpha is the extensionless link
# Redirect to NEW format
RewriteCond %{IS_SUBREQ} false
RewriteCond %{QUERY_STRING} id=([a-zA-Z]+)
RewriteRule ^index\.php$ %1? [R=301,L]

# Redirect back to "usable link"
RewriteRule ^([a-zA-Z]+)$ index.php? id=$1 [L]
[/quote]

That code is well commented and explained in the text.

Modifying that for your generic (lowercase) filenames:

# Assumes "usable link" is something.html
# and something is the extensionless link
# Redirect to NEW format
RewriteCond %{IS_SUBREQ} false
RewriteRule ^([a-z]+\.html$ %1 [R=301,L]

# Redirect back to "usable link"
RewriteRule ^([a-z]+)$ $1.html [L]

This non-looping “loopy redirection” is stopped from looping by the RewriteCond’s check for “already redirected” and will handle any of your lowercase.html files. I would also recommend that your redirection back include a check that the file exists as an html file with its own RewriteCond statement: The status code in the first RewriteRule will cause that redirection to be shown (and picked-up by search engines to update their database) while the lack of a status code in the second will prevent the redirection from being shown.

# Redirect back to "usable link" RewriteCond $1\.html -f RewriteRule ^([a-z]+)$ $1.html [L]

That’s only a bit more advanced than the tutorial but, if you’ve gone through it, you would fully understand each and every directive used - only the {IS_SUBREQ} is specific to this example.

WARNING: I always advise members NOT to “play script kiddie” and use code which is not understood. If you have questions, PLEASE be sure to ask before using in a production environment (test to your heart’s content offline but using code you do not understand online is a dangerous … and stupid … thing to do!).

Regards,

DK

1 Like