How to handle both /url and /url/ redirects with htaccess?

200 Views Asked by At

I am rewriting all URLs and shorthand some of them:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(([^\.]+))\.pl [NC]
RewriteRule ^(.*)$ http://%1.pl%{REQUEST_URI} [R=301,L]
RewriteRule ^test$ test-page.php [R=301,L]

so that example.pl/test redirects to example.pl/test-page.php

but example.pl/test/ redirects to example.pl/

while it should: example.pl/test/ redirects to example.pl/test-page.php

How to handle both /url and /url/ redirects?

I assume that it has to something with trailing slash.

2

There are 2 best solutions below

0
On

Try this:

RewriteEngine On
RewriteRule ^(.*)/$ http://%{HTTP_HOST}/$1 
RewriteRule ^test$ test-page.php [R=301,L]

Tested here.

3
On

You need to make trailing slash optional using /?$ regex. Try these rules:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.pl [NC]
RewriteRule ^ http://%1.pl%{REQUEST_URI} [R=301,L]

RewriteRule ^test/?$ test-page.php [NC,R=301,L]

Make sure to test this in a new browser to avoid 301 caching issues.