Reputation: 361
Assuming a string like http://domain.com/aaaa/bbb/ccc/ddd
I want to use a .htaccess file to get the last element, in this case ddd.
I am using:
RewriteRule (.*)/$ ?pt=$1 [L]
But it only works with a trailing slash.
Upvotes: 1
Views: 4928
Reputation: 2872
It works:
RewriteEngine On
RewriteRule ^([A-Za-z0-9]+)$ /index.php?content=$1 [L]
It will change the following URL:
http://example.com/anypage
into
http://example.com/index.php?content=anypage
But it'll override everything and ignore parameters. Therefore it's better to add an extra restrictions.
Upvotes: 1
Reputation: 14447
That's because your regex includes a trailing slash.
Try:
RewriteRule ([^/]+)/?$ ?pt=$1 [L]
The question mark after the slash means "zero or one". If you don't want that behavior, change the regex accordingly.
Edit:
Because the rewrite directives will be re-run after a rewrite is done (at least in per-directory context), it is important to ensure that a rule will not be re-run after you have already achieved the desired rewrite. There are multiple ways to accomplish this goal, but one is:
RewriteCond %{QUERY_STRING} !pt
RewriteRule ([^/]+)/?$ ?pt=$1 [L]
The point of the RewriteCond
is to prevent the RewriteRule
from being applied when there is already a query string with pt
in it somewhere, which would be a clue that the rewrite has already happened. More complicated rules might require more or different RewriteCond
directives.
Upvotes: 5