Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess add trailing slash and force www with clean urls

Tags:

php

.htaccess

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.

like image 818
imns Avatar asked Dec 10 '10 16:12

imns


2 Answers

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.

like image 156
Leniency Avatar answered Sep 27 '22 21:09

Leniency


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>
like image 37
Kirill Artemenko Avatar answered Sep 27 '22 21:09

Kirill Artemenko