.HTACCESS MOD_REWRITE FLat Links Issue
I am having a few problems re-writing flat links using htaccess, I have two sets of rules which independently work perfectly well but when put together have an undesirable effect.
The first section adds a trailing forward slash if one is absent and re-writes the url with a 301 divert.
The second converts all of the ‘folders’ into parameters which is then passed to php in a particular format.
We have an unknown number of folders depending on the page so wish to keep the code generic.
The problem is that although the code functionality works (i.e. php is fed the correct parameters) the url is re-written in the wrong format.
Php code:
&开发者_Go百科lt;?php echo ‘<pre>’;print_r($_GET); echo ‘</pre>’;?>
Sample url: (removed HTTP:// as restricted to two links per question)
localhost/foo/bar
is re-written to
test.localhost/foo&other[]=bar/
with output:
Array
(
[p] => foo
[other] => Array
(
[0] => bar
)
)
If you remove the first section for the htaccess then the output is the same and the url remains:
localhost/foo/bar
HTACCESS:
Options +FollowSymlinks
RewriteEngine on
SECTION 1:
RewriteCond %{REQUEST_URI} !.*/$
RewriteRule (.*)$ /$1/ [L,R=301]
SECTION 2:
RewriteRule ^(.*)/([^/]+)/?$ $1&other[]=$2 [L]
RewriteRule ^(?!index\.php)([^/]+)/?$ /index.php?p=$1 [L,QSA]
Try these lines instead:
Options +FollowSymlinks
# Activate Rewrite Engine
RewriteEngine on
# Force trailing slash to be present (only if such file does not exist)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [R=301,QSA]
# Rewrite rule to real php file (only if such folder does not exist)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9\-_]+)/([a-z0-9\-_]+)/$ /index.php?p=$1&other[]=$2 [NC,QSA,L]
Please note, the last line will only work for URLs of this structure: /foo/bar/
. It will not work with /foo/bar
(this should never happen as we have special Redirect rule to add trailing slash) as well as with longer URLs like /foo/bar/meow/
-- you would need to duplicate and modify last 2 lines.
Also, if there is a folder that matches URL (e.g. foo/bar/
) then rule will not work as well.
These rules were tested and confirmed to be working. Let me know if you need any modifications.
精彩评论