Mobile app version of vmapp.org
Login or Join
Angie530

: Rewrite everything that is not a file I want to have everything that looks like this: /1/2/3/4/5/[...] to redirect to this: /index.php?u=/1/2/3/4/5/[...] unless the requested string is a specific

@Angie530

Posted in: #Apache #ModRewrite

I want to have everything that looks like this:

/1/2/3/4/5/[...]


to redirect to this:

/index.php?u=/1/2/3/4/5/[...]


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.

10.02% popularity Vote Up Vote Down


Login to follow query

More posts by @Angie530

2 Comments

Sorted by latest first Latest Oldest Best

 

@Ogunnowo487

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=/[CO] [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=/[CO] [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=/[CO] [L]


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

10% popularity Vote Up Vote Down


 

@Becky754

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:

^.*..*$ -> /[CO]

[stop matching if found]

^.*$ -> /index.php?u=[CO]


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

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme