php-URL重写不适用于Apache
作者:互联网
我想要以下内容:
myhomepage.com<-这应该变成这个-> myhomepage.com/index.php
myhomepage.com/mypage<-应该转到此-> myhomepage.com/index.php?page=mypage
myhomepage.com/mypage/mymethod<-应该转到此-> myhomepage.com/index.php?page=mypage\u0026amp;method=mymethod
myhomepage.com/api/logout<-应该转到此-> myhomepage / api / logout.php
这是我的.htaccess文件:
RewriteEngine On
RewriteBase /
RewriteRule ^/api/(.*)$api/$1.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*)$index.php?page=$1&method=$2&item=$3
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$index.php?page=$1&method=$2
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$index.php?page=$1
一切正常,但使用api的规则似乎无效.
更新1:
RewriteRule ^/api/(.*)$api/$1.php
当我调用myhomepage.com/api/logout时,它将其重写为myhomepage.com/index.php?page=api\u0026amp;method=logout
更新2:
我的第一个想法是,也许有类似默认的rewrite_module的东西.它将所有不是文件的内容重写为index.html或类似的内容.特别是当我使用XAMPP时.
更新3:
经过一番试验后,我发现我无法使用api来调用它,因为它是一个目录.例如,当我使用myhomepage.com/ap/logout和RewriteRule ^ ap /(.*)$api / $1.php重写它时,它可以正常工作.有什么想法如何使目录名称起作用吗?
更新4:
我将链接todo.js(从Windows / System32 / drivers / etc中的主机)重定向到127.0.0.1
然后我编辑了httpd-vhosts.conf并添加了以下内容:
<VirtualHost todo.js:80>
ServerAdmin slajaa09@htlkaindorf.at
DocumentRoot "C:/xampp/htdocs/todo"
ServerName todo.js
ServerAlias todo.js
</VirtualHost>
我的api文件夹是htdocs / todo的子目录
*解决方案:*
这是我的问题的最终解决方案:
ErrorDocument 404 /error.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule api/([^/]+)/?$api/$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/(.+)/(.*)$index.php?page=$1&method=$2&item=$3 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/(.*)$index.php?page=$1&method=$2 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$index.php?page=$1 [L,QSA]
特别感谢anubhava!
解决方法:
.htaccess中的前导斜杠不匹配,因为.htaccess是针对每个目录指令的,并且Apache从RewriteRule URI模式中剥离当前目录路径(因此为前导斜杠).
在DOCUMENT_ROOT / .htaccess文件中使用以下规则:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule api/([^/]+)/?$api/$1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/(.*)$index.php?page=$1&method=$2&item=$3 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/(.*)$index.php?page=$1&method=$2 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$index.php?page=$1 [L,QSA]
标签:apache,mod-rewrite,php,regex,url-rewriting 来源: https://codeday.me/bug/20191122/2059124.html