简体   繁体   中英

Limit direct access to directory using .htaccess

I have the following folder structure where I have a web app running:

/root/public/index.php

I have a .htaccess in the /root that redirects all requests to /root/public but I am also able to access my content by prepending the /public directory in my request for example at the moment I can do

  • www.example.com/public/index.php
  • www.example.com/index.php

Both lead to the same resource but I only want people to access the resource by going to and return an error if they try to directly access the /public directory

www.example.com/index.php

My current .htaccesss look like this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ public/ [L]
</IfModule>

What am I missing here to stop the accessibility of my /public folder via URLs?

I have tried applying some rewrite rules used by WordPress` but that didn't work for my use-case by following the guide here: https://wordpress.org/documentation/article.htaccess/

You can do something like this:

RewriteEngine On

# Block direct requests to the "/public" subdirectory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^public/ - [F]

# Rewrite all requests to "/public/index.php"
RewriteRule ^ public/index.php [END]

(The <IfModule> wrapper is not required and should be removed.)

The check against the REDIRECT_STATUS environment variable ensures that only direct requests (from the user) are checked and not rewritten requests by the later rewrite.

Note that I changed your existing rule to rewrite the request directly to /public/index.php since that would seem to be the intention. (Rather than relying on the DirectoryIndex .)

Although, I'm wondering how you are managing your static assets (if any)?

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