Forum Moderators: phranque

Message Too Old, No Replies

mod rewrite Question: Simple redirect after 1st slash with exclusions

         

NeedExpertHelp

4:07 am on Dec 18, 2009 (gmt 0)

10+ Year Member



Hello,

I'm trying to redirect anything after the 1st slash to my script, but with certain exclusions.

For example, I want to redirect:

[mydomain.com...]

to

[mydomain.com...]

I first tried doing:

---------------------------------------------
RewriteRule ^/(.*) /script.php?var=$
---------------------------------------------

But that was also redirecting the script.php file itself.

I then tried:

---------------------------------------------
RewriteCond %{REQUEST_URI} !^/(.*)\.php
RewriteCond %{REQUEST_URI} !^/(.*)\.css
RewriteCond %{REQUEST_URI} !^/(.*)\.gif
RewriteRule ^(.*)$ /script.php?var=$1
---------------------------------------------

Which excludes .php, .css, and .gif files, but it was also redirecting the homepage to script.php.

I have a feeling this can be easily done without RewriteCond and with a simple one-line RewriteRule, but I just can't figure out how.

Any and all help would be appreciated.

Thanks!

jdMorgan

7:56 pm on Dec 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Combine the RewriteConds eliminating the redundant regex, and change the rule pattern so that at least one character is required in the URL-path. That will prevent "/" from being rewritten. Always use an [L] flag on your rules, unless you know why [L] must not be used.

RewriteCond $1 !\.(gif¦css¦php)$
RewriteRule ^(.+)$ /script.php?var=$1 [L]

The filetypes in the rewritecond are arranged in 'most-likely-to-be-requested' order for efficiency. The order shown is typical; Check your server stats to verify.

Make sure your script can return proper content for robots.txt, favico.ico, and sitemap.xml requests, all of which are presumed to exist by all major search engines. If not, these need to be excluded from your rule as well. Consider also .jpg and other media files, pdf files, etc.

Replace the broken pipe "¦" characters with solid pipes before use; Posting on this forum modifies the pipe characters.

Jim

g1smd

7:59 pm on Dec 18, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



And beware that 'redirecting to a script' is actually an 'internal rewrite', not an 'external redirect'.