Tag Archives: mod_rewrite

Stop Annoying favicon.ico 404 errors

If you’re like me, you don’t like cluttering your main folder with unnecessary files. This is why I hate that some browsers are still looking for ‘favicon.ico’ in the main folder even when you indicate in <head> that’s not where the agent should be looking…

Here is a way to eliminate those PITA 404’s from your error logs… Continue reading

Use .htaccess to force SSL and WWW prefix

Just a quick snippet showing how to force the HTTPS protocol (SSL) and the “www” sub-domain…

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

There are other ways to achieve the same result, but I find this method is clean and requires the least amount of overhead to incorporate.

My ultimate .htaccess file for CodeIgniter 2.0

#Initialize mod_rewrite
RewriteEngine On
RewriteBase /

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

#Re-route forbidden urls
RewriteCond %{REQUEST_URI} ^(system|application).* [OR]
RewriteRule ^(.*)$ index.php?/$1 [L]

#Re-route urls if file/directory does not exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Rewrite all unresolvable URLs to a script using .htaccess

Another simple one.

The following code checks to see if the request is for a real directory or file and reroutes the request to “/myscript.php” if not.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ myscript.php?/$1 [L]
</IfModule>

Take note of the the excamation point (it means “not”). To do the opposite (reroute valid directory/file requests through a script) just change the rewrite conditions (RewriteCond) to…

Continue reading

Force “www” subdomain using .htaccess

Short and sweet.

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

And if you want to remove the “www” portion, just change the condition (RewriteCond) and rule (RewriteRule)…

You may ask “Why should I do this?” and the asnwers are simple. It promotes linking uniformity and ensures you don’t end up being negatively affected by having “duplicate content” across (sub)domains in search engine indexes.

.htaccess redirect query string using mod_rewrite to another query string

I recently had the need to redirect one query string to another query string. The reason for this was we created a new item in our Zen Cart software that took the place of 3 other items. To make sure the search engines and our visitors reached the new product instead of the old ones, the following code was used to redirect them accordingly.

Continue reading