Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Use php (instead of .htaccess) to internally redirect to query string? Re: Use php (instead of .htaccess) to internally redirect to query string?

#93986
gno
Member

As Tcooper says, it’s not entirely possible.

On a traditional http-server setup URLs are a relative path to a given file on the server. When you write http://website.com/video/music-video it will look for a file or directory in the path webserver-root/video/music-video.

What you could do is to forward all requests to a single router file, like Tcooper also adviced. This way you only need one rule in your .htaccess file and you can do all the routing within php.

My favorite way of doing it is somewhat like this – calling the path to the http servers root ./

1) Create a series of folders in ./ which can contain your app files. Only one required is a folder called public.

2) Create the file ./.htaccess containing:


RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]

3) Create the file ./public/.htaccess containing:


RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

4) Create the file ./public/index.php which will handle the requests.

What this means is that all requests to http://www.website.com will actually hit website.com/public/index.php – but the user will never see this. The ./.htaccess files forwards all requests to our fake-root folder ./public/. The ./public/.htaccess file forwards all requests not found as being folders or files in the public-folder will be pushed to the ./public/index.php file.

That means, if you have a file ./public/css/style.css this will be accessible on http://www.website.com/css/style.css. This is due to the two RewriteCond rules from 3.

Querystrings can be read from the $_GET variable in ./public/index.php – Remember that you should never trust input from users – not even URLs. Check the querystring before you use it for anything.

You can set up a series of constant to make working with this new structure easier. For example this code in ./public/index.php:


define('ROOT',  dirname(dirname(__FILE__)) . '/');
define('APP', ROOT . 'app' . '/');

require(APP . 'somefile.php'); // pointing to ./app/somefile.php

Doing it this way means that no matter where you type require(SOMECONSTANT . ‘somefile.php’); it will always point to the same file.

This setup provides you with the least bad solution to your original problem and furthermore it gives you a solid foundation for a secure website.

Sorry for the wall of text. But I hope this will be helpful to you.