I am trying to get something similar to $_SERVER["PATH_INFO"] but weird server issues are preventing me from using it...
In my application, the links can look like
www.domain.com/folder/file/variable
www.domain.com/folder/file
www.domain.com/file/variable or
www.domain.com/file/
With .htaccess, I a开发者_StackOverflowm trying to get to the proper pages, and not to redirect to the index.php or similar.
So far, I have this, which is not working :)
RewriteRule ^(.+)$ /$1.php # page only
RewriteRule ^(.+)/(.+)$ /$1.php?x=$2 # page + variable
RewriteRule ^(.+)/(.+)$ /$1/$2.php # folder / page
RewriteRule ^(.+)/(.+)/(.+)$ /$1/$2.php?x=$3 # folder / page + variable
I am sure I need to use RewriteCond %{REQUEST_FILENAME} -f to check if the request is a filename, or directory... but I was unable to make it work...
Variables can contain all weird characters - that is why i am matching with dot... Maybe I should try to match file / folder names with a-z only ( since i do not think they will ever contain anything but a-z, _ or - ).
Any help is greatly appreciated, since its been almost two days of agony now :)
Reverse the Rewrite Rule the most specific to the first.
RewriteEngine On
RewriteRule ^(.+)/(.+)/(.+)$ /$1/$2.php?x=$3 [L]
# RewriteRule to check that the file is exists here
RewriteCond %{REQUEST_URI} ^(.+)/(.+)$
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI}.php -f
RewriteRule ^(.+)/(.+)$ /$1/$2.php [L]
# If file is not exists, then check by put to the variable
RewriteRule ^(.+)/(.+)$ /$1.php?x=$2 [L]
RewriteRule ^(.+)$ /$1.php [L]
Most people/frameworks pass everything that does not have an extension specified to a single php front controller that then works out what to do. I think one reason most people go this route is because of simply how complex mod_rewrite is!
thanks to @LazyOne's hint, I was able to solve this.
htaccess file now looks something like this:
RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)$ /$1/$2.php?x=$3
RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)/$ /$1/$2.php
RewriteRule ^([-a-zA-Z0-9_]+)/([-a-zA-Z0-9_]+)$ /$1.php?x=$2
RewriteRule ^([-a-zA-Z0-9_]+)/$ /$1.php
all folder or files paths must end with "/" while variable must not. this is not a problem in my framework - but might not be useful for others.
精彩评论