Man.. I'm at a loss. I have a basic rewrite flow that I can't seem to get working. I want to check if a rea开发者_运维知识库l-file exists. If it does, serve it, but if it doesn't, reroute to a PHP file. Here's my .htaccess file:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/application%{REQUEST_URI} !-f
RewriteRule ^(.*)$ core/index.php?f=%{DOCUMENT_ROOT}/application%{REQUEST_URI} [QSA,L]
RewriteRule (.*) application/$1 [L]
My directory structure is as follows:
.
├── [drwxr-xr-x] application
│ └── [-rw-r--r--] test.html
├── [drwxr-xr-x] core
│ ├── [-rw-r--r--] index.php
│ └── [drwxr-xr-x] tmp
│ ├── [-rw-r--r--] httpd-access.log
│ ├── [-rw-r--r--] httpd-error.log
│ └── [-rw-r--r--] rewrite.log
└── [-rw-r--r--] .htaccess
3 directories, 6 files
Here are the permission I would appreciate any help. Thanks.
Are you sure your Apache has mod rewrite turned on?
Maybe you can add RewriteBase / or RewriteBase %{DOCUMENT_ROOT} directive right after RewriteEngine On
To be placed in .htaccess in root folder. If you going to place in in config file (inside <VirtualHost>
for example) then it needs to be slightly modified.
RewriteEngine On
RewriteBase /
# 1) do not do anything for existing file or folder
RewriteCond %{ENV:REDIRECT_STATUS} !^$
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]
# 2) real file (in application folder) -- rewrite path
RewriteCond %{DOCUMENT_ROOT}/application%{REQUEST_URI} -f
RewriteRule (.*) /application/$1 [L]
# 3) nope, no such file -- serve via index.php
RewriteRule ^(.*)$ /core/index.php?f=%{DOCUMENT_ROOT}/application%{REQUEST_URI} [QSA,L]
The important thing that many people forgetting about, is the fact that after URL was rewritten it goes to next iteration. And on such next iteration URL is already different to the originally requested. These rules should take care about this moment.
This is how it will work for /test.html
:
- Rule #1 will be skipped as there is no
/test.html
- Rule #2 will work, as there is a file
/application/test.html
. Rewrite goes to next iteration ([L]
flag). - Rule #1 will work as URL now is
/application/test.html
and such file does exist. This rule tells Apache to stop rewriting any further -- job done.
This is how it will work for /meow.html
:
- Rule #1 will be skipped as there is no
/meow.html
- Rule #2 will be skipped as there is no file
/application/meow.html
. - Rule #3 will work -- URL rewritten to
core/index.php?f=%{DOCUMENT_ROOT}/application/meow.html
. Rewrite goes to next iteration ([L]
flag). - Rule #1 will work as URL now is
/core/index.php
and such file does exist. This rule tells Apache to stop rewriting any further -- job done.
EDIT:
You may add leading slash /
before destination part of RewriteRule (should be no difference ... but your setup could be a bit different from mine).
精彩评论