How to access directory's index.php without a trailing slash AND not get 301 redirect

前端 未结 2 828
庸人自扰
庸人自扰 2020-12-16 15:15

I have this structure: site.com/api/index.php. When I send data to site.com/api/ there is no issue, but I imagine it would be better if the api wou

相关标签:
2条回答
  • 2020-12-16 15:38

    You'd first need to turn off directory slash, but there's a reason why it is very important that there's a trailing slash:

    Mod_dir docs:

    Turning off the trailing slash redirect may result in an information disclosure. Consider a situation where mod_autoindex is active (Options +Indexes) and DirectoryIndex is set to a valid resource (say, index.html) and there's no other special handler defined for that URL. In this case a request with a trailing slash would show the index.html file.But a request without trailing slash would list the directory contents.

    That means accessing a directory without a trailing slash will simply list the directory contents instead of serving the default index (e.g. index.php). So if you want to turn directory slash off, you have to make sure to internally rewrite the trailing slash back in.

    DirectorySlash Off
    
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.*[^/])$ /$1/
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^api/(.*)$ api/index.php [L]
    

    The first rule ensures that the trailing slash gets appended to the end, though only internally. Unlike mod_dir, which externally redirects the browser, the internal rewrite is invisible to the browser. The next rule then does the api routing, and because of the first rule, there is guaranteed to be a trailing slash.

    0 讨论(0)
  • 2020-12-16 15:42

    If you do not want to use the solution provided by Jon Lin (reconfiguring all your URLs pointing to directories), you could use the following code (note the ? in the regexp - it basically says that the trailing slash after "api" is optional). I have not tested it, but it should work as it is:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^api/?(.*)$ api/index.php [L]
    
    0 讨论(0)
提交回复
热议问题