【问题标题】:htaccess shows 404 error rather than finding index.phphtaccess 显示 404 错误而不是找到 index.php
【发布时间】:2021-12-21 16:10:30
【问题描述】:

我在重写 URL 时遇到了一些问题

我想用我的.htaccesshttp://localhost:81/es/index.php 变成http://localhost:81/index.php?lengua=es,以帮助页面搜索引擎优化

这是我目前的.htaccess


<FilesMatch ".*\.(log|ini|htaccess)$">
    deny from all
</FilesMatch>

Options -Indexes
RewriteEngine On
RewriteBase /
FallbackResource "index.php"

RewriteRule ^(en|es|pt)?/?(.*)?$ $2?idioma=$1 [QSA,L]

我已经检查过它们是否与 htaccess tester 一起工作并且它们按预期工作,但是当我浏览页面时它显示“找不到文件”。错误(我有index.php,我没有es/index.php

由于我的输出 URL 是 http://localhost:81/index.php?lengua=es 我不明白为什么它不起作用

【问题讨论】:

  • 您服务器的 error_log 文件中是否有这些请求的内容?
  • 这条规则有什么作用吗?您的.htaccess 文件中还有其他指令吗? .htaccess 是否启用覆盖? (是否启用了 mod_rewrite?)
  • @StephenOstermiller 错误/apache 日志仅显示 404 错误错误日志输出:code[Wed Nov 10 19:12:09.685194 2021] [proxy_fcgi:error] [pid 93:tid 140126253808360] [ client 172.24.0.1:41464] AH01071: Got error 'Primary script unknown', referer: localhost:81/index_traducciones.phpcode "/index_traducciones.php" 在 url 中不使用 /es 时完美运行
  • @StephenOstermiller 另外,重写规则是以前测试的保留,它不会改变结果,它仍然存在,因为我有时会在测试时更改规则的正则表达式(我只是评论了它,同样结果)
  • @MrWhite 和斯蒂芬一样,是以前测试的遗留物,我已经重写了 mod,我当前的完整 .htaccess 是: 拒绝所有 选项 -Indexes RewriteEngine On RewriteBase / FallbackResource "index.php" #RewriteCond %{REQUEST_URI} "\/en\/|\/es\/|\/pt\/" RewriteRule ^(en |es|pt)?/?(.*)?$ $2?idioma=$1 [QSA,L]

标签: apache .htaccess mod-rewrite


【解决方案1】:

我建议在四个重写规则中打破这一点:

RewriteEngine on

# Redirect to add the trailing slash to language directory
# http://example.com/es  > http://example.com/es/
RewriteRule ^/?(en|es|pt)$ /$1/ [R=301,L]

# Redirect to remove `index.php`
# http://example.com/es/index.php  > http://example.com/es/
RewriteRule ^/?(en|es|pt)/index\.php$ /$1/ [R=301,L]

# Handle requests for the base language directory
# http://example.com/es/  > http://example.com/index.php?idioma=es
RewriteRule ^/?(en|es|pt)/$ /index.php?idioma=$1 [QSA,L]

# Handle requests for php files within the language directory
# http://example.com/es/foo.php  > http://example.com/foo.php?idioma=es
RewriteRule ^/?(en|es|pt)/(.+\.php)$ /$2?idioma=$1 [QSA,L]

我会删除 RewriteBase /,因为我相信这是根 .htaccess 文件中的默认值。

我会删除FallbackResource "index.php",因为根据您提供的示例,您不需要它。如果您保留它,文档中的示例会显示它以斜杠开头:FallbackResource /index.php。您也应该在没有它的情况下进行测试,因为它可能与重写规则发生冲突。

我总是喜欢用可选的斜杠^/?(而不仅仅是^)开始重写规则,这样它们就可以在.htaccesshttpd.conf 中使用而无需修改。

问题中的规则使 一切 都是可选的,包括语言代码。我的规则不是(en|es|pt)?,而是使用(en|es|pt),因此如果语言代码不在URL 中,它们匹配。

我的规则不是让语言目录后面的斜线可选,而是在它存在和不存在时做不同的事情。

在您的规则中,(.*)?完全等同于更简单的(.*)。我将其更改为(.*\.php),以便它只匹配 PHP 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 2021-11-29
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多