Tom S.
Tom S.

Reputation: 13

Using Apache mod_rewrite to send all requests to a file

How can I use mod_rewrite to send certain types of incoming urls to a particular file on the server?

Ideally any html requests would load a file (eg /var/www/sites/urlprocessor.php) which would then determine what is being requested and the display the appropriate content based on the url.

Example: Say I wanted a url to list some 'cars'. I would want the following URLs to load the urlprocessor.php file instead of loading the actual page and instead of doing a redirect.

http://www.mydomain.com/cars.html --> /var/www/sites/urlprocessor.php
http://www.mydomain.com/cars.htm  --> /var/www/sites/urlprocessor.php
http://www.mydomain.com/cars      --> /var/www/sites/urlprocessor.php

On the flip-side, non-html requests (jpgs, pdfs, etc) would continue on normally without loading the urlprocessor.php file.

I am currently using the last line of code in the following to accomplish this. It 301 redirects all html page requests to 'index.html' which then loads the urlprocessor.php file. I prefer to just load the file without the 301 redirect.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^mydomain\.com
RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]
RewriteRule !^.*(\.gif|\.GIF|\.png|\.mp3|\.m3u|\.js|\.jpg|\.JPG|\.css|\.swf|\.flv|\.ico|\.wav|\.doc|\.DOC|\.pdf|\.PDF|\.xls|\.XLS|\.txt|\.TXT)$ index.html [L]

Is there a way to go directly to a file without doing the redirect?

Thanks!!

Tom

Upvotes: 1

Views: 1579

Answers (1)

Prix
Prix

Reputation: 19528

Given that /var/www/ is the root folder then this would work:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . /sites/urlprocessor.php [L]

Basically this will redirect any non-existent folder and file to the urlprocessor.php

For more information on how to handle the redirect with your PHP you can refer yourself to this answer.

Upvotes: 2

Related Questions