【问题标题】:.htaccess file is causing 404 errors with AJAX.htaccess 文件导致 AJAX 出现 404 错误
【发布时间】:2013-08-13 17:50:09
【问题描述】:

一切都在我的本地主机上运行,​​其中没有使用 .htaccess 文件。但是当我访问实际站点时,我遇到了 AJAX 请求的问题。我发现导致问题的部分是删除 .php 扩展名。

这是我的 .htaccess 文件

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /

## redirect to 404 page when file does not exist
ErrorDocument 404 /404.php

## clean urls for blog.php
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+blog\.php\?title=([^\s&]+)&? [NC]
RewriteRule ^ /blog/%1? [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^blog/([\w-+]+)/?$ /blog.php?title=$1 [L]

## remove index.php
RewriteCond %{THE_REQUEST} ^.*/index.php 
RewriteRule ^(.*)index.php$ /$1 [R=301,L] 
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index$ /$1 [R=301,L]

## To remove .php file extension
## RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
## RewriteRule ^ %1 [R,NC]
## RewriteCond %{REQUEST_FILENAME}.php -f
## RewriteRule ^ %{REQUEST_URI}.php

通过注释掉最后四行,它解决了问题。但我希望能够删除 .php 并仍然将 ajax 用于表单之类的东西。

这里是ajax

$.ajax({
     type:'post',
     url:'inc/example.php',
     data:$data,
     async:false,
     success:function(){
         console.log('success');
     },
     error:function(r){
         console.log(r.responseText);
     }
});

ajax 中的错误函数正在显示我的 404 错误页面。我尝试从 ajax 请求中的 url 中删除 .php,不好。然后我尝试导航到 inc/example.php 并得到 404 页面。 .htaccess 文件位于根目录,发出ajax请求的页面是根目录下的一个目录,因此404错误发生在两个目录深处。

【问题讨论】:

    标签: .htaccess jquery mod-rewrite


    【解决方案1】:

    您需要排除重定向 POST 请求。您的 ajax 代码通过 POST 提交到 example.php,当规则将您重定向到没有 php 扩展名的 URL 时,您将丢失请求正文。您应该使条件仅与 GET 和 HEAD 请求匹配:

    ## To remove .php file extension
    RewriteCond %{THE_REQUEST} ^(GET|HEAD)\s([^.]+)\.php [NC]
    RewriteRule ^ %2 [R,NC]
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^ %{REQUEST_URI}.php
    

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2014-05-08
      • 2018-10-11
      • 2019-12-10
      相关资源
      最近更新 更多