从特定网址使用htaccess删除.php扩展名

时间:2017-02-02 07:48:08

标签: php ajax apache .htaccess

我在.htaccess文件中编写了一些工作正常的规则,我写的规则是:

# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\s/+(\S+?)\.php(/\S*)?\sHTTP [NC]
RewriteRule ^ /%1%2 [L,R=301,NE]

# check to see if the request is for a PHP file:
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^/?(.+?)(/.*)?$ /$1.php$2 [L]

问题:我遇到的唯一问题是它正在从每个网址中删除.php扩展名,因此我的Ajax请求不断获得404.

例如:在一个方面,Ajax调用是针对Ajax/x.php之类的网址,但由于上述规则,它会转换为Ajax/x并返回404。

所以现在不是从所有文件中删除.php扩展名,而是从{2}文件a.phpb.php中删除.php扩展名。

对社区需要一些帮助,我知道我几乎就在那里。任何帮助都将受到赞赏

2 个答案:

答案 0 :(得分:1)

要从2个特定文件中删除.php扩展名,您可以使用:

RewriteCond %{THE_REQUEST} /(a|b)\.php [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [L]

答案 1 :(得分:0)

First of all, when you remove the php extension from any url, you have to submit the form by changing removing the .php extension from the action such as
<form class="form-horizontal" method="post" action="new_team" enctype="multipart/form-data">
Same thing also will apply to the ajax file such as
 $.ajax({
            url: 'php/contact_form_submit',
            type: 'post'

.htaccess should look like this
Options +MultiViews
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
# RewriteRule ^([^/]+)/$ http://url/$1 [R=301,L]
RewriteRule ^([^/]+)/$ http://url/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
# RewriteRule ^(.+)\.php$ http://url/$1 [R=301,L]
RewriteRule ^(.+)\.php$ http://url/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]

so try it out and let me know if it solved