Write .htaccess OK?

I’m newbie.
I’m building website by PHP/MySQL. While i setup file .htaccess, it have this code. However i don’t know right or wrong?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/ $1 [R=301,L]

Who can help me know it right or wrong?


What is your problem with this code?

It appears that you’re trying to do two operations with a single RewriteRule: Redirect 404’s to ??? and force non-www’d URLs.

Personally, I’d use (assuming 404.php as your 404 handler):

RewriteEngine on # Ensure not in comment mode

# enforce non-www
RewriteCond %{HTTP_HOST} !^example\\.com$ [NC] # excellent
RewriteRule .? http://example.com%{REQUEST_URI} [R=301,L]
# you don't need to capture the Apache value you already have ({REQUEST_URI})

# handle 404's
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# RewriteCond %{REQUEST_FILENAME} !-l - symbolic links are rarely used so this is superfluous
RewriteRule .? /404.php?uri=$1 [R=301,L]
# the 404.php will be looked for in the server root THEN in your DocumentRoot
# I retained the {REQUEST_URI} for 404.php to deal with as you see fit

What did you do wrong? You ANDed all your conditions with the “catch all” in the rule but the redirection loops on the {REQUEST_URI} value so you also need to provide an exit to the loop (other than your file and directory tests).

For more information, please have a read of the mod_rewrite tutorial Article linked in my signature. It’s received rave reviews from all members except one (see next post?).



Here’s full Tips and Tricks for your. Htaccess File: allcodingtips.com/tips-and-tricks-for-your-htaccess-file/ .Hope this will solve your issue.

Those examples are pretty bad. Mostly because of spaces in the code that shouldn’t be there / be somewhere else, plus some stuff that’s blatantly wrong, like All Options + Indexes, which must be Options + Indexes (i.e., without the All at the start).