简体   繁体   中英

How to write conditionally path based htaccess rewrite to specific php file

My requirement is that when a request came {{host}}/t1/batch that time it should read from batch.php else any request should read from index.php. My base dir is t1 . I am doing some experiment in htaccess. I am missing proper regular expression.

RewriteBase /t1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(batch|index)/?$ $1.php [L,NC]

This can be achieved with the following rules:

RewriteCond %{REQUEST_URI} ^/t1/batch/$
RewriteRule ^.*$ %{DOCUMENT_ROOT}/batch.php [L,NC,END]
RewriteRule ^.*$ %{DOCUMENT_ROOT}/index.php

I do not see the need for RewriteBase here.

You can get it done with the following lines:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/t1/batch/?$
RewriteRule ^(.*)$ batch.php [L,NC]

If you have batch.php under t1 directory and the path is like http://{host}/t1/batch.php , you need to add RewriteBase line:

RewriteBase /t1

If you're not going to add RewriteBase line, you will have to follow absolute path like:

RewriteRule ^.*$ /t1/batch.php [L,NC]

Hope you understand and got the solution.

Assuming t1 is a sub-directory of your document root, in /t1/.htaccess put this:

RewriteEngine on
RewriteBase /t1/
# no rewrites for real files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [NS,L]
# batch
RewriteRule ^batch(?=$|/) $0.php [NS,L]
# everything else
RewriteRule ^(?!index\.php$). index.php [NS,L]

If you have any rewriting in /.htaccess , as well, you will need to ignore the t1 sub-directory in that file with a rule like:

RewriteRule ^t1(?:$|/) - [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM