5
votes

I'm using my htaccess file with mod_rewrite to create clean urls like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

I would also like to force the site to have the 'www' subdomain and most importunately add a trailing slash if the url doesn't have one.

I am an absolute noob with mod_rewrite and I've tried accomplishing this on my own by combining other code I found on google (sad I know), but I always end up with a 500 error.

Here's the code I found for force www:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.domain\.tld$ [NC]
RewriteRule ^(.*)$ http://domain.tld/$1 [R=301,L]
</IfModule>

Thanks for your help.

2
Do either of them work alone? Find out which set of rules is breaking it.profitphp
I know the first one works, and I think the second one does too. I'm just not sure how to combine it all to get the outcome I want.imns

2 Answers

11
votes

Try separating out the www and the trailing slash check. This is tested and hopefully working for you. You didn't say if you're running placing at domain root or in a subdirectory - usually good info when asking for help with htaccess.

RewriteEngine On

# Assuming you're running at domain root.  Change to working directory if needed.
RewriteBase /

#
# www check
# If you're running in a subdirectory, then you'll need to add that in
# to the redirected url (http://www.mydomain.com/subdirectory/$1

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

#
# Trailing slash check

# Don't fix direct file links
RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301]

#
# Finally, forward everything to your front-controller

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [QSA,L]

To debug, comment out the individual sections and see what is/isn't working.

2
votes

Use this and forgot your problems ;)

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://your-domain.ru/$1/ [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>