【问题标题】:htaccess removing .php extension and pretty urlshtaccess 删除 .php 扩展名和漂亮的 url
【发布时间】:2019-03-03 14:30:01
【问题描述】:

我试图同时删除 .php 扩展名。所以例如“http://localhost/timetable/login”而不是“http://localhost/timetable/login.php

但也有

http://localhost/timetable/38/”而不是 "http://localhost/timetable/index.php?week=38"

我能够让其中一个或另一个工作,但不能同时工作。我假设它是因为它们之间存在冲突,但我不够先进,无法找到它。

这是我的 .htaccess 文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
RewriteRule ^([0-9]+)$ index.php?week=$2 
RewriteRule ^([0-9]+)/$ index.php?week=$2

如果我在地址栏中输入“http://localhost/timetable/38”,它会将我带到“http://localhost/38/”并出现找不到对象错误。

有谁知道问题出在哪里?

更新:我现在可以转到该页面,但是

echo $_GET['week'];

返回空结果,所以它忽略了“http://localhost/timetable/40”中的 40

【问题讨论】:

  • 听起来很奇怪,无法用您发布的规则来解释。必须有其他的重写规则。请将这些添加到问题中。
  • 只需删除文件的倒数第二行并将最后一行替换为:
  • @arkascha 没有其他规则就是整个文档。
  • @Martin 我试过了,但没有帮助。
  • 我相信应该是 1 美元而不是 2 美元。试试看:RewriteRule ([0-9]+)/?$ index.php?week=$1 [QSA,L]

标签: regex .htaccess


【解决方案1】:

当您尝试获得一周时,您只有一个捕获组。所以应该是 $1 而不是 $2。

根据this test tool,以下应该可以工作:

RewriteRule ([0-9]+)/?$ index.php?week=$1

我会这样做:

# rewrite if url ends with a number and possibly a slash
RewriteRule ([0-9]+)/?$ index.php?week=$1 [QSA,L] 

# do not append .php if it already ends with .php, other add .php
RewriteCond %{REQUEST_URI} !\.php$ 
RewriteRule ^(.*)$ $1.php [QSA,L]

【讨论】:

  • 我收到错误“在此服务器上找不到请求的 URL /38。”
  • 另外,如果您只使用RewriteRule ([0-9]+)/?$ index.php?week=$1 而之前没有 RewriteCond?它可能不起作用,我从答案中删除了它。
  • RewriteCond %{REQUEST_URI} !\.php$ # 如果 .php 已经以 .php 结尾,则不要附加 .php 导致内部服务器错误
  • 对不起,我的错误。必须删除规则背后的 cmets。请检查是否回答了主要问题。它适用于 1 美元而不是 2 美元吗?
  • 是的,它在本地主机上,但不在我的服务器上,但我遇到了另一个问题,即我的服务器在与我的网站相同的目录中没有读取我的 .htaccess 文件,因此我试图解决这个问题立即发布。
【解决方案2】:

您应该考虑将所有输入作为单个字符串路由到某个 php 文件,而不是为每个输入使用单独的重写规则。

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?page=$1 [L,QSA]

在您的 php 文件中,您可以将字符串分隔为输入并根据需要使用它们。

<?php
$inputs = explode('/', $_GET['page']);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2020-02-27
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 2016-07-10
    • 2014-03-04
    相关资源
    最近更新 更多