1

Is there a way I can use PHP (and/or .htaccess) to rewrite the URL of a page.

For example if a user goes to www.mysite.com/french they are actually accessing the page which is www.mysite.com/index.php?lang=fr

But not a redirect.

3 Answers 3

3

You want to use mod_rewrite and an .htaccess file to achieve this.

RewriteEngine On
RewriteBase /
RewriteRule ^french/(.*)$ /index.php?lang=fr [L,QSA]
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, using Apache mod_rewrite and appropriate rules in an .htaccess file.

The docs on mod_rewrite are here: http://httpd.apache.org/docs/current/mod/mod_rewrite.html

Comments

0

on the Apache site you can find several examples of URL rewriting flavors, by the way it's enough to use something like this in an .htaccess file:

RewriteEngine on
RewriteRule ^french(/|)$ /index.php?lang=fr  [flag]

Where [flag] can be one of the following:

[PT]
[L,PT]
[QSA]
[L,QSA]

You may want to have a look at the PT (passthrough) flag docs or RewriteRule flags docs.

Also, pay attention to what your links are pointing to: in fact, the RewriteRule first argument is a regular expression that will be used to match the URLs to be rewritten. At the moment,

^french(/|)$

matches "french", right after the domain name,followed either by a slash (/) or nothing (that's the meaning of (/|) ); that is, it'll match www.mysite.com/french and www.mysite.com/french/ but nothing else. If you need to parse query string arguments, or subpaths, then you may need a more complex regex.

6 Comments

That's not what the [PT] flag is used for. httpd.apache.org/docs/current/rewrite/flags.html#flag_pt
@Rocket: mod_rewrite is actually a URL-to-filename resolver. Whatever it rewrites stuff to is, by default, the end result. [PT] is a bit of a hack to allow it to do URL-to-URL rewrites that then get passed back into Apache for further processing by modules like mod_alias. It does seem a bit out of place here, though.
@cHao: I know what [PT] does. I was commenting that "stops Apache from redirecting to the page while silently loading it" doesn't really make sense.
@Rocket: Yeah, i didn't get that either. I was semi wondering why i never see (or had a need to use) [PT] in .htaccess files, but apparently it's always on at that point.
@Michael I added some extra info, btw could you post the failing URLs?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.