Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

apache - How do I redirect a URL that isn't found without sending a 404 header?

My website needs a .htaccess file that will redirect a user to index.php when a page is not found. However, I do not want Apache to send a 404 header with the document.

I asked this question earlier: Apache .htaccess 404 error redirect

The command "ErrorDocument /index.php" produces the exact effect that I want, except that it sends a 404 header with the page. What can I do? Should I overwrite the 404 header with PHP?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
  1. enable rewrite
  2. check if requested file exists as a regualar file with size (not empty)
  3. check if requested file is link
  4. check if requested file is a directory
  5. if one of the previous 3 statements is true show that file
  6. otherwise go to index.php

If the redirect to index.php happens u can get the requested uri by using $_SERVER["REQUEST_URI"] inside index.php

  • '-d' (is directory) Treats the TestString as a pathname and tests if it exists and is a directory.
  • '-f' (is regular file) Treats the TestString as a pathname and tests if it exists and is a regular file.
  • '-s' (is regular file with size) Treats the TestString as a pathname and tests if it exists and is a regular file with size greater than zero.
  • '-l' (is symbolic link) Treats the TestString as a pathname and tests if it exists and is a symbolic link.
  • '-F' (is existing file via subrequest) Checks if TestString is a valid file and accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to determine the check, so use it with care because it decreases your servers performance!
  • '-U' (is existing URL via subrequest) Checks if TestString is a valid URL and accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to determine the check, so use it with care because it decreases your server's performance!

More information: http://httpd.apache.org/docs/current/mod/mod_rewrite.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...