【问题标题】:.htaccess redirect everything except certain request.htaccess 重定向除某些请求之外的所有内容
【发布时间】:2012-11-04 08:56:16
【问题描述】:

我的.htaccess 文件有问题。它通过我的index.php 页面重定向所有内容,这是我想要的大多数请求。

但唯一一次我不想重定向是通过 AJAX 调用。

它通过我的index.php 文件重定向任何请求,如下所示:
RewriteRule /.* /index.php [NC,L]

AJAX请求地址为:
http://myurl.dev/login/ajax/functions.php

附目录结构:
/modules/login/ajax/functions.php

我对正则表达式和 RewriteRules 缺乏经验,并且已经阅读/尝试了许多具有不同逻辑的变体,但无法阻止 /ajax/ 中的任何内容不重定向到索引页面。

我在 Index RewriteRule 之前尝试了 RewriteCond 以重定向到索引,除非 /ajax/ 但没有运气。

Rewrite Cond %{REQUEST_URI} !(.*)/ajax
RewriteRule /.* /index.php [NC,L]

还为 /ajax/ 请求尝试了单独的 RewriteRule:
RewriteRule ^(.*)/ajax/functions\.php$ /modules/$1/ajax/functions.php [NC,L]

所以到目前为止没有任何工作,它要么重定向到index,要么点击500 server error

有没有人有任何建议或链接可以帮助?谢谢。

注意:当我说重定向时,我并不是指完整的页面刷新,因为我知道 Apache 不会在没有 [R] 标志的情况下进行完整的 url 刷新。

-- 编辑:工作文件--

这是我的完整 .htaccess 代码:

Options +FollowSymLinks  
RewriteEngine on

# Intercept any requests to the core, and keep them being written to the core (so they don't go to index.php)
RewriteRule ^core/(.*)$ core/$1 [NC,L]

# The magic, stops any requests to a file for being redirected.
# needed to be under the /core/ redirect
RewriteCond %{SCRIPT_FILENAME} !-f

# Rewrite all requests to index.php.
RewriteRule /.* /index.php [NC,L]

# Some requests (without trailing slashes) can fall through the above rule. This bit catches those stragglers.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ /$1/ [L,R=301]

ErrorDocument 404 /404/

【问题讨论】:

    标签: php jquery ajax regex .htaccess


    【解决方案1】:

    使用

    RewriteCond %{SCRIPT_FILENAME} !-d //excludes existing directories
    RewriteCond %{SCRIPT_FILENAME} !-f //excludes existing files
    

    在任何 RewriteRule 之前。这将排除任何已经存在的目录或文件,因此RewriteRule 将不适用于http://myurl.dev/login/ajax/functions.php,因为它确实存在,但它将适用于http://myurl.dev/someOtherNonExistantFile.php

    这使它成为您的完整 .htaccess 文件代码:

    AuthType Basic
    Options +FollowSymLinks  
    RewriteEngine on
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-f
    # Intercept any requests to the core, and keep them being written to the core (so they don't go to index.php)
    RewriteRule ^core/(.*)$ core/$1 [NC,L]
    
    # Rewrite all requests to index.php.
    RewriteRule /.* /index.php [NC,L]
    
    # Some requests (without trailing slashes) can fall through the above rule. This bit catches those stragglers.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(.*)/$
    RewriteRule ^(.*)$ /$1/ [L,R=301]
    
    ErrorDocument 404 /404/
    

    【讨论】:

    • 好主意,刚刚尝试过,但是 php 类、css 和 js 文件需要 /core/ 重定向。由于RewriteCond %{SCRIPT_FILENAME} !-f,它没有正确重定向到这些文件,因此加载这些文件时出现 404。我将这个 RewriteCond 移到 /core/ RewriteRule 下面,所有文件都正确加载,现在重定向工作正常。谢谢!使用工作文件更新问题。
    猜你喜欢
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多