简体   繁体   中英

wildcard .htaccess and reject some address on subdomain

I want all file or directory existed under up.example.com subdomain rejected and show 404 error.

Also I want all another request point to index.php .

I write this code:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ - [R=404,L,NS]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L,QSA]

When I test this code for http://up.example.com/test.jpg

If test.jpg file existed on root server, show me this error:

Not Found
The requested URL /test.jpg was not found on this server.
Apache Server at up.example.com Port 80

It's ok!
But when test.jpg not existed, give me this error:

Not Found
The requested URL /index.php was not found on this server.
Apache Server at up.example.com Port 80

Instead open index.php ( index.php exist on root)

Why? and how can I fix it?

Try this one

RewriteEngine On

RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC]  # remove if it is not related to subdomain
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L,QSA]

RewriteCond %{HTTP_HOST} ^up\.(.+)$ [NC]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^(.*)$ - [R=404,L,NS]

Actually the problem is that you write everything to index.php and that becomes a valid file in the request. When mod_rewrite runs next time first rule sends it to 404.

To overcome this error have your rules like this:

RewriteEngine On

# if it is valid file or directory except for index.php
# then send 404 to browser
RewriteCond %{HTTP_HOST} ^up\. [NC]
RewriteCond %{THE_REQUEST} \s/+index\.php[?\s] [NC]
RewriteRule ^index\.php$ - [R=404,L,NC]

RewriteCond %{HTTP_HOST} ^up\. [NC]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule !^index\.php$ - [R=404,L,NC]

# send all non-file/directories to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [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