2

I have looked for the answer to my problem here, but the solution is always provided without explaining how to do it, that's the reason I can not do it properly.

I have this code:

RewriteRule ^dex/([^_]*)/([^_]*)/([^_]*)/([^_]*)/([^_]*)$ /dex.php?one=$1&two=$2&three=$3&four=$4&five=$5 [L]

This htaccess as it is makes it mandatory that all parameters are given. This URL works:

http://example.com/dex/one/two/three/four/five

I also want to make it work like this:

http://example.com/dex/one/two/three/four

Making the last (or some) parameters optional. I read something about QSA|qsappend here: http://httpd.apache.org/docs/current/en/rewrite/flags.html#flag_qsa but I can't understand it completely.

Any help? Thank you

Lucas
  • 193
  • 2
  • 9

2 Answers2

4

To anyone having the same issue, this is the code used to fix it:

RewriteRule ^dex/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?([^/]*)?$ /dex.php?one=$1&two=$2&three=$3&four=$4&five=$5 [L]

Changed ([^_]*) to ([^/]*) and added ? after what I wanted to make optional.

In this case: /? is making a end slash optional, and ([^/]*)? is making the last parameter optional. So it works when the URL is like this:

http://example.com/dex/one/two/three/four/

http://example.com/dex/one/two/three/four

http://example.com/dex/one/two/three/four/five

http://example.com/dex/one/two/three/four/five/

Hope this helps someone.

Lucas
  • 193
  • 2
  • 9
0

Rewrite rules use regular expressions. These regular expressions are always tiresome and difficult to maintain. The following, for example, is an answer to question about regex parsers on HTML, and the difficulty you may find with them:

RegEx match open tags except XHTML self-contained tags

Your htaccess file is an Apache configuration file. It should be used for simple configuration, and not for programming. Have it point to the code, and then let the code do the rest. For example, your .htaccess file:

RewriteRule ^(.*)$ index.php [QSA,NC,L]

And, if you're using PHP with index.php...

$objects = explode('/', ltrim($_SERVER[REDIRECT_URL], '/'));

print_r($objects);    // list of items from URL

You may end up wanting to grab a different SERVER parameter, but you'll want to keep this complicated stuff in the code, not in configuration files.

Community
  • 1
  • 1
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133