Home > Blockchain >  Allow-Origin does not work when folder exists
Allow-Origin does not work when folder exists

Time:04-20

Consider a page served by apache2 on http://localhost/htaccess-test for example.

The folder might look like this:

htaccess-test
 |- .htaccess
 |- index.php

And this is the .htaccess:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, PATCH, OPTIONS"

RewriteEngine on
RewriteRule ^ index.php [QSA,L]

Every call gets be redirected to index.php and handled from there by PHP (or whatever).

Now spawn a client on a different port or host:

<html>
<body>
    <script>
      (function() {
        const xhttp = new XMLHttpRequest();
        xhttp.open("PUT", "http://localhost/htaccess-test/foo");
        xhttp.send();
      })();
    </script>
</body>
</html>

Works. But if you add a folder 'foo' to the page's folder ('htaccess-test'), the call results in a CORS-error!

Can anynone help me to avoid this! I have an Endpojnt which has the name 'test' and that conflicts with the test-folder...

CodePudding user response:

xhttp.open("PUT", "http://localhost/htaccess-test/foo");

If /foo is a physical directory then mod_dir will issue a 301 redirect to append the trailing slash. The redirect response won't have the CORS headers set since you are not using the always condition with the Header directive, hence the CORS error.

However, I expect you don't want the trailing slash in the first place, so you need to prevent mod_dir from appending the trailing slash.

Add the following at the top of the .htaccess file:

# Prevent mod_dir appending a trailing slash to directories
DirectorySlash Off

However, since you are disabling the directory slash, you need to ensure that directory listings are also disabled since the presence of a DirectoryIndex document (in that directory) will no longer prevent mod_autoindex from generating a directory listing (if the trailing slash is omitted). Add the following at the top of the .htaccess file (if you don't have it already):

# Prevent mod_autoindex from generating directory listings.
Options -Indexes

If you need to access any directories directly then you'll need to manually append the trailing slash as required (with an external redirect or internal rewrite).

  • Related