Question

I'm changing

mydomain.com/directory/?name=lorem&action=posts

to

mydomain.com/directory/lorem/posts

But I'm now trying to add one called "other"

so I would like to get

mydomain.com/directory/?name=lorem&action=posts&other=38291389

to

mydomain.com/directory/lorem/post/38291389

This is the .htaccess code I am using for the first example

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^(\w+)(/(\w+))?$ /directory/?name=$1&action=$3

and here's the one I tried to make for the second example, but it doesn't work

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^(\w+)(/(\w+))?$ /directory/?name=$1&action=$3&other=$4

Could somebody help me get this to work?

Was it helpful?

Solution

Keep it simple:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} -d [OR] 
RewriteCond %{SCRIPT_FILENAME} -f [OR]
RewriteRule .* - [L]

RewriteRule ^(\w+)/(\w+)/(\w+)/?$ /directory/?name=$1&action=$2&other=$3
RewriteRule ^(\w+)/(\w+)/?$ /directory/?name=$1&action=$2
RewriteRule ^(\w+)/?$ /directory/?name=$1

There is no real gain in combining multiple effects in a single regex (although it is clever and makes you feel good) but when the regex engine does its work, the clever regex may take more time to match than 2 or 3 simpler rules (as above).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top