Niklas R
Niklas R

Reputation: 16870

mod_rewrite condition for existing folder

I'm trying to set-up an .htaccess file that will pass every request URL as GET into a file called index.php. The only exception is, when the request URL points to a directory res.

Examples:

/wiki/cool-stuff          => index.php?uri=/wiki/cool-stuff
/wiki/cool-stuff?news=on  => index.php?uri=/wiki/cool-stuff&news=on
/res/cool-photo.jpg       => res/cool-photo.jpg

Two problems:

  1. The GET variable passed to /wiki/cool-stuff in the second example is not passed to index.php
  2. Accessing /res (not /res/!!) suddenly shows me /res/?uri=res in my browser and index.php with uri=res/. Accessing /res/ instead, shows me index.php with uri=res/ and the URL in the browser stays (which is okay).

The .htaccess:

RewriteEngine on
RewriteBase   /subthing/

RewriteCond   %{REQUEST_URI}    !/res/(.+)$
RewriteCond   %{REQUEST_URI}    !index.php
RewriteRule   (.*)              index.php?uri=$1 

How can I achieve the desired behaviour?

Upvotes: 0

Views: 195

Answers (1)

Scott Stevens
Scott Stevens

Reputation: 2651

  1. Try using the Query-String-Append flag, QSA

  2. Make the trailing slash optional - in Regex, this is achieved by adding ?.

New .htaccess:

RewriteEngine on
RewriteBase   /subthing/

RewriteCond   %{REQUEST_URI}    !/res(/.*)?$
RewriteCond   %{REQUEST_URI}    !index.php
RewriteRule   (.*)              index.php?uri=$1 [QSA]

Note that I have tweaked the Regex on the /res folder to cause /resabc to be redirected (if the slash was the only optional piece, anything beginning with res would match.

Apache Mod_Rewrite Documentation

Upvotes: 1

Related Questions