Home > Blockchain >  htaccess root of url issue
htaccess root of url issue

Time:04-04

Trying to achieve rewrites for 3-1 paths in the url, and then a rewrite for index. Can achieve the former with below:

RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^([^/] )/([^/] )/([^/] )?$ /index.php?a=$1&b=$2&c=$3 [L,QSA,NC]
RewriteRule ^([^/] )/([^/] )?$ /index.php?a=$1&b=$2 [L,QSA,NC]
RewriteRule ^([^/] )?$ /index.php?a=$1 [L,QSA,NC]

Want to add after this a rewrite from index (eg "www.domain.com") to /index.php?a=10 but cant get that work.

CodePudding user response:

RewriteRule ^([^/] )?$ /index.php?a=$1 [L,QSA,NC]

The "problem" is that the last rule also matches an empty URL-path so the request is rewritten to /index.php?a= and any later rule that matches the root is not processed.

Instead of writing the rule to match the root "after" the existing rules, you can add it before your existing rules to avoid conflict. For example:

RewriteRule ^$ /index.php?a=10 [QSA,L]
: other rules follow...

RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^([^/] )/([^/] )/([^/] )?$ /index.php?a=$1&b=$2&c=$3 [L,QSA,NC]
RewriteRule ^([^/] )/([^/] )?$ /index.php?a=$1&b=$2 [L,QSA,NC]
RewriteRule ^([^/] )?$ /index.php?a=$1 [L,QSA,NC]

Note that the RewriteCond directive only applies to the first RewriteRule directive. Do you need this at all?

Your rules are a little ambiguous since in each of the regex you are allowing the last path segment to be optional. This basically means the trailing slash is optional (eg. /foo/bar/ and /foo/bar are both valid URLs according to these rules). If you don't make the path segment optional in the last rule then you can place your rule to match the root last as you were wanting to do originally.

A request for /foo/bar/baz matches the first rule. /foo/bar/ (with a trailing slash) also matches the first rule, but /foo/bar (no trailing slash) matches the second rule. Likewise, /foo/ also matches the second rule, but /foo matches the third rule. And (following the same pattern) the third rule also matches / (hence your initial problem). My point is... should that last path segment on each rule be optional?

  • Related