Webmasters Stack Exchange is a question and answer site for pro webmasters. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to have everything that looks like this:


to redirect to this:


unless the requested string is a specific file. So anything that doesn't have a . (dot), I want to redirect to index.php?u=[...]. I'll then parse the URI segments in PHP to determine what the user is requesting.

I've been looking around for how to do this, but have only a very rough understanding of regular expressions and have been unable to find an example of how to do it.

share|improve this question

Nevermind, figured it out. I found it's easier to match if something is in a string rather than if it isn't in a string, so this is what I came up with:

^.*\..*$ -> /$0

[stop matching if found]

^.*$ -> /index.php?u=$0

Not correct syntax of course, but you can easily adapt it to any number of rerouting systems.

share|improve this answer

In Apache mod_rewrite you can check if the request is for a physical file with a condition such as:

RewriteCond %{REQUEST_FILENAME} -f

This is better than checking for a . (dot) in the filename - which could simply be present in the URL. To negate an expression simply prefix it with !. So, !-f matches if the file does not exist.

To internally rewrite everything else to index.php?u=XXX, where XXX is the original request then add:

RewriteCond %{QUERY_STRING} !^u=
RewriteRule .* index.php?u=/$0 [L]

The RewriteCond directive is necessary to prevent a rewrite loop and basically checks that ?u= is not already present in the requested URL. Note that this is an "internal rewrite" - the URL in the address bar does not change. To externally redirect add the R flag on the RewriteRule, ie [R,L].

Bringing this all together in a .htaccess file in the document root:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} !^u=
RewriteRule .* index.php?u=/$0 [L]

If you only want to do this for specific URLs then modify the RewriteRule pattern (the first argument). So, for URLs that look like /1/2/3/4/5/[...]:

RewriteRule ^1/2/3/4/5.* index.php?u=/$0 [L]

The slash prefix on the pattern should be omitted for per-directory .htaccess files.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.