Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

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

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 would work without the trailing slash also, like this: site.com/api. This causes a 301 redirect and thus loses the data (since data isn't forwarded). I tried every re-write I could think of and couldn't avoid the redirect. This is my current re-write rule (though it may be irrelevant).

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

Can I make this url work and maintain the post data without using the trailing slash?

Some rewrites that didn't work: (all still redirect)

RewriteRule ^api$ api/index.php [L] 
RewriteRule ^api/*$ api/index.php [L]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...