Moozoo
Moozoo

Reputation: 497

htaccess pretty urls setup

I'm using htaccess for the first time to make pretty urls for my website html files and 1 php file. I was just wondering if I would be able to get some advice on my htaccess file set up and if how I have it set up is a good way? I'd hate for my urls to not work in some situation because of what I have written. :(

Example html file:

before:  http://www.domain.com/subdomain/htmlpage.html
after:   http://www.domain.com/subdomain/htmlpage/

Single php file:

before:  http://www.domain.com/subdomain/phppage.php?p=1
after:   http://www.domain.com/subdomain/phppage/1/

I have added in a rule to redirect index.html to index.php. I've also had to add 'base href' in the head of each file because I've used relative links.

the htaccess file:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^index\.html?$ / [NC,R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)/$ $1.html [L]
RewriteRule ^(.+)/([0-9]+)/?$ phppage.php?p=$1 [L]

Upvotes: 1

Views: 2682

Answers (2)

Ulrich Palha
Ulrich Palha

Reputation: 9509

try adding the following to your .htaccess file in the root of your domain

Options +FollowSymLinks

RewriteEngine On
RewriteBase /

# redirect http://www.domain.com/subdomain/htmlpage.html to http://www.domain.com/subdomain/htmlpage/
RewriteCond %{REQUEST_URI} ^(/subdomain/[^/]+)\.html$ [NC]
RewriteRule . %1/ [L,R=301]


#redirect http://www.domain.com/subdomain/phppage.php?p=1 to http://www.domain.com/subdomain/phppage/1/
RewriteCond %{REQUEST_URI} ^(/subdomain/[^/]+)\.php$ [NC]
# or alternatively if page is literally phppage uncomment below and comment above
#RewriteCond %{REQUEST_URI} ^(/subdomain/phppage)\.php$ [NC]
RewriteRule . %1/ [L,R=301]

#if url does not end with /
RewriteCond %{REQUEST_URI} ^(/subdomain/.+[^/])$ [NC]
# and its not for an existing file
RewriteCond %{REQUEST_FILENAME} !-f
# put one trailing slash
RewriteRule . %1/ [L,R=301]

#write http://www.domain.com/subdomain/htmlpage/ to htmlpage.html
RewriteCond %{REQUEST_URI} ^/subdomain/([^/]+)/$ [NC]
RewriteRule . %1.html [L]   


#write http://www.domain.com/subdomain/phppage/1/ to phppage.php?p=1
RewriteCond %{REQUEST_URI} ^/subdomain/[^/]+/([0-9]+)/$ [NC]
RewriteRule . phppage.php?p=%1 [L]  

Upvotes: 1

This line

RewriteRule ^(.+)/([0-9]+)/?$ phppage.php?p=$1 [L]

is going to send some pages to phppage.php even though they don't look like

http://www.domain.com/subdomain/phppage/1/

because there is no mention of phppage in the first argument to RewriteRule.

Upvotes: 1

Related Questions