Smart URL with optional parameters?

2019-07-20 17:16发布

I currently have this in my .htaccess file:

RewriteEngine On 
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\w+)(/(\w+))?/?$ route.php?1=$1&2=$3 [L]

So I can do myurl.com/foo/bar(/) or just myurl.com/foo(/) (optional trailing slash, can't lose)

I'm not very familiar with regular expression, so how would I have this allow up to around 6 parameters (myurl.com/one/two/three/four/five/six)?

1条回答
【Aperson】
2楼-- · 2019-07-20 17:38
RewriteRule ^(\w+)(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?/?$ route.php?1=$1&2=$2&3=$3&4=$4&5=$5&6=$6 [L]

You can check it here


To allow spaces in the parameters you can use:

RewriteRule ^([\w\ ]+)(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?/?$ route.php?1=$1&2=$2&3=$3&4=$4&5=$5&6=$6 [L]
查看更多
登录 后发表回答