RewriteRule when transferring files from root to another directory

Viewed 23

Previously, a lot of project files was in the the root directory. Including the following files was in the root:

index.php
make.php

In order to make file structure more logical, the above files have been moved to the /operation/ folder.

Question: how to write a redirect rule in .htaccess if I want the following links to still work correctly:

https://example.com/ 
https://example.com/?var=value 
https://example.com/make.php

And so that the client does not even guess that, in fact, the access goes to files:

https://example.com/operation/
https://example.com/operation/?var=value
https://example.com/operation/make.php

If I specify rules like this in the .htaccess file:

RewriteEngine On
RewriteRule ^/?$ /operation/
RewriteRule ^/(.*\.php)$ /operation/$1

then https://example.com/ works normally, but https://example.com/make.php does not work.

2 Answers

The URL-path matched by the RewriteRule pattern does not start with a slash in per-directory .htaccess files, so the regex ^/(.*\.php)$ never matches and the request is not rewritten.

However, your question text states 3 URLs that need to be rewritten, but the code you've posted looks like it is intended to match "any" .php file. Is that the intention? Or would this conflict with other .php files in the root directory?

https://example.com/ 
https://example.com/?var=value 
https://example.com/make.php

To rewrite these 3 URLs, you would do the following:

RewriteEngine On
RewriteRule ^(index\.php)?$ /operation/index.php [L]
RewriteRule ^(make\.php)$ /operation/$1 [L]

You should rewrite directly to the file that handles the request, ie. index.php in the first rule. Otherwise, you are reliant on mod_dir issuing an additional internal subrequest for the DirectoryIndex. The first rule catches both requests for / and /index.php. The query string is passed through by default.

Don't forget the L flag, otherwise, processing continues (unnecessarily).

This solution worked for me:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)$ /operation/$1 [NC]
Related