Apache Mod rewrite help
I've been working on a solution to this for several hours now & figured if someone doesn't mind helping me out, it might save me some time. My question is with regards to Apache mod_rewrite; of course there is tons of documentation out there, however nothing specific to my requirements which are:
to take a URL in this format:
language/pagename.php
(language will either be 'english' or 'french', I will write a separate rule for each. [only need an example for one though]. page name will 开发者_JAVA技巧be any word character (w+)
. all URLs will have a .php
extension).
And then rewrite it so the URL doesn't change in the users browser, but so that php could receive it in this format:
language/page.php?slug=pagename
e.g. so $_GET['slug']
would return the value pagename
, and all requests are then handled by page.php.
So far my best guess is
RewriteEngine On
RewriteBase /
RewriteRule ^english/(\w+).php$ english/page.php?slug=$1
However this make php tell me that slug=page
for this URL for example english/financial.php
; rather than financial
.
Have tried a bunch of other regex conventions too (.)
instead of w
& so on..
Use these rules:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(english|french)/([^/\.]+)\.php$ /$1/page.php?slug=$2 [NC,QSA,L]
This needs to be place in .htaccess file in root folder. If you will be placing it config file (e.g.
httpd-vhost.conf
, inside<VirtualHost>
directive), then rule needs to be slightly altered.This rule should work for any language, as long as you add it into the rule (
english|french
part).This rule has a condition which will not rewrite if such file already exists. This should solve your problem with
slug=page
: in your rule you most likely have a rewrite loop (after rewrite occurs it goes to the next iteration -- that's how mod_rewrite works, and you need to have some logic in place to break this loop). Instead ofRewriteCond %{REQUEST_FILENAME} !-f
you could useRewriteCond %{REQUEST_URI} !^/(english|french)/page\.php [NC]
but it is a bit more difficult to maintain (you need to add languages here as well as in rewrite rule itself).If you already have some other rewrite rules then take care with placing these in correct place (order of rules matters).
Because I do not know for sure what page names (slugs) would be, I've used this pattern:
[^/\.]+
(any characters except/
or.
) .. but you may change it to\w+
or whatever you think will be better.Rule preserve any optional page parameters (query string) -- useful for preserving referrals/tracking code etc.
精彩评论