Ash Ash - 3 months ago 10
Apache Configuration Question

.htaccess rewrite rule not working without trailing slash?

I have the follow URLs:

www.website.com/index.php?section=index
www.website.com/index.php?section=freebies
www.website.com/index.php?section=deals
www.website.com/index.php?section=articles


and the following pagination url parameter for each:
page=1
for example

www.website.com/index.php?section=freebies&page=1


I am using the rewrite rules below to change the URL to:

www.website.com/freebies/1 etc


www.website.com/freebies/1
and
www.website.com/freebies/
work correctly
but if I remove the trailing slash for example:

www.website.com/freebies


It is showing
www.website.com/freebies/?section=freebies&page=1


How can I stop this from happening.

My rewrite rules:

RewriteRule ^([0-9]+)/?$ index.php?section=index&page=$1 [NC,L]
RewriteRule ^freebies/?$ index.php?section=freebies&page=1 [L]
RewriteRule ^articles/?$ index.php?section=articles&page=1 [L]
RewriteRule ^deals/?$ index.php?section=deals&page=1 [L]
RewriteRule ^freebies/([0-9]+)/?$ index.php?section=freebies&page=$1 [NC,L]
RewriteRule ^articles/([0-9]+)/?$ index.php?section=articles&page=$1 [NC,L]
RewriteRule ^deals/([0-9]+)/?$ index.php?section=deals&page=$1 [NC,L]

Answer

freebies appear to be a real directory and Apache's mod_dir module adds a trailing slash for directories causes a redirect thus exposing your internal URL to clients.

You can use:

RewriteEngine On

# internally add a trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L]

RewriteRule ^([0-9]+)/?$ index.php?section=index&page=$1 [NC,L,QSA]
RewriteRule ^freebies/?$ index.php?section=freebies&page=1 [L,NC,QSA]
RewriteRule ^articles/?$ index.php?section=articles&page=1 [L,NC,QSA]
RewriteRule ^deals/?$ index.php?section=deals&page=1 [L,QSA,NC]
RewriteRule ^freebies/([0-9]+)/?$ index.php?section=freebies&page=$1 [NC,L,QSA]
RewriteRule ^articles/([0-9]+)/?$ index.php?section=articles&page=$1 [NC,L,QSA]
RewriteRule ^deals/([0-9]+)/?$ index.php?section=deals&page=$1 [NC,L,QSA]
Comments