【问题标题】:Rewriting page urls in website重写网站中的页面网址
【发布时间】:2025-12-16 12:05:02
【问题描述】:

我创建了一个简单的网站,其中一些页面 url 的格式为“*.php”。

我想将我的网址 /home.php 设为 /home。我可以在.htaccess 文件中执行此操作吗?

我在这里添加我的代码

<files campus_config.ini>
order allow,deny
deny from all
Allow from 127.0.0.1
</files>

<files student.ini>
order allow,deny
deny from all
Allow from 127.0.0.1
</files>

<FilesMatch (variables|mysql)\.php>
order allow,deny  
deny from all
</FilesMatch>

RewriteEngine on
RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

示例网址: localhost/test/campus/login.php(test是一个文件夹,campus是我的项目文件夹,.htaccess文件在我的项目文件夹中)

【问题讨论】:

  • 但是当我在 .htaccess 文件中尝试相同时,它给了我一个错误“/home is not found on this server”,请帮助
  • 一个解决方案(虽然不是最好的):httpd.apache.org/docs/2.2/mod/core.html#forcetype
  • @Linblow ,我没有得到解决方案,你能解释一下你提到的,谢谢你的回复:)
  • @Vishnu 你在运行 Apache 还是 IIS?
  • @LIUFA,我正在使用 Apache

标签: php .htaccess


【解决方案1】:

您正在寻找的内容称为 URL 重写。这通常由应用程序服务器完成,通常是 Apache 或 IIS(在 Windows 上)。 how to do it in Apache。在 Windows 上,它取决于所使用的 IIS 版本 (6-8)。

【讨论】:

  • ,抱歉回复晚了,我用的是Apache
【解决方案2】:

将此行放在您的/test/campus/.htaccess

RewriteEngine on
RewriteBase /test/campus/

RewriteCond %{THE_REQUEST} /(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ $1.php [L]

【讨论】:

  • 我将在这里发布我的代码,RewriteEngine on RewriteRule ^home\.php$ home [L],我需要在apache中启用内容协商模块吗?
  • 嗨 Anubhava,谢谢,我试过了。但它仍然给我错误“在此服务器上找不到请求的 URL /home”。即使更改了 url,它也在寻找 home home.php的
  • 您在浏览器中输入的是什么 URL,这个 .htaccess 文件的位置是什么?还有更多规则吗?
  • 我将 .htaccess 放在项目目录中(存在于父目录中)。这是我在 .htaccess 顺序中的全部代码允许,拒绝所有允许来自 127.0.0.1 的允许 order allow,deny deny from all Allow from 127.0.0.1 order allow,deny deny from all RewriteEngine on RewriteCond %{THE_REQUEST} \s/+(?:index)?(.*?)\.php[\s?] [NC] RewriteRule ^ /%1 [R=301,L,NE] RewriteCond %{REQUEST_FILENAME} ! -d RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC] RewriteRule ^(.+?)/?$ /$1.php [L]
  • 无法理解来自 cmets 的任何代码。编辑您的问题并在那里提供。 projects 也是 DocumentRoot 下的子目录吗?