Question

I am writing my very first htaccess and would like help cleaning it up and understanding it. The first issue I am having is with mulitple parameters. my current setup looks like:

Options +FollowSymLinks

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)$ index.php?p1=$1 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2&p3=$3 [L]

RewriteCond %{REQUEST_FILENAME} !/(_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)$ index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

Is there a way to simplify this to handle up to a maximum of 4 parameters with all of them being optional? Which leads me to me next problem that it seems that if you need to have a trailing slash after the parameters unless you are using all 4 parameters.

In short I would like my urls to look like this...

http://www.example.com/home
http://www.example.com/home/
http://www.example.com/blog/i-am-a-title
http://www.example.com/blog/i-am-a-title/
http://www.example.com/varable1/varable2/varable3/varable4
http://www.example.com/varable1/varable2/varable3/varable4/

I'll appreciate any help that you can provide.

Était-ce utile?

La solution

Well this is sort of an experiment, it will work as you have said but I believe there may be a better way to do this:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)/
RewriteRule ^(([^/]*)/?)(([^/]*)/?)(([^/]*)/?)(([^/]*)/?)$ /index.php?p1=$2&p2=$4&p3=$6&p4=$8 [L]

Basically I am adding an extra group per entry so you can safely exclude a non existent group.

So the first element is required and is $2, the second element becomes $4, the third element becomes $6 and the last element becomes $8.

(([^/]*)/?) this basically means that anything not a / that ends or not with / for the outer group and inner group anything not a /.

Simplified the rule a bit more:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)/
RewriteRule ^([^/]*|)/?([^/]*|)/?([^/]*|)/?([^/]*|) /index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

Autres conseils

As long as you don't mind that there will be blank parameters, you can use look-aheads for all of your paramaters:

RewriteCond %{REQUEST_FILENAME} !/(index\.php|_modules|css|files|ico|img|js)
RewriteRule ^(?:([^/]+)|)(?:/([^/]+)|)(?:/([^/]+)|)(?:/([^/]+)|) index.php?p1=$1&p2=$2&p3=$3&p4=$4 [L]

The problem with these being optional is that you're rules will loop once, which makes the first capture group index.php. To avoid this you need to add index.php as part of the exlusion in the condition.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top