.htaccess 从 URL 中删除文件扩展名和变量

.htaccesss Remove the File Extension and Variables From the URL

我知道这个问题已经被问过很多次了,但无论我怎么尝试,我的代码仍然无法正常工作。我有这个 .htaccess 文件,我想从此重定向我的代码:

example.com/news/articles.php?id=21&artName=Hello-World

对此:

example.com/news/articles/21/Hello-World

目前我的 .htaccess 文件中有这段代码:

Options -MultiViews
RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^news/articles/([\w-]+)/(.+) news/articles.php?id=&artName= [QSA,L,NC]

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule !\.php$ %{REQUEST_URI}.php [QSA,L]

这是这篇文章的 href link:

<a href="https://www.example.com/news/articles/21/Hello-World">Article</a>

每当我尝试转到该页面时。我收到“错误 404 - 未找到”页面。我是编辑 .htaccess 文件的新手,所以请让我知道我在代码中做错了什么,这样我就可以在我的 link 中看到成功重写,谢谢。

假设您已经按照注释中的说明在指令上添加了 news/ 前缀,那么您还需要删除以下规则块:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ .php [L]

这是不正确的,将导致跳过以下对 /news/articles.php 的重写。无论如何,这与后来的指令做同样的事情(后来的指令“更好”)。

您可以在 .htaccess 顶部尝试此操作以禁用 mod_spelling 选择:

<IfModule mod_speling.c>
   CheckSpelling off
   CheckCaseOnly off
</IfModule>

Options -MultiViews
RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

RewriteRule ^(news/articles)/([\w-]+)/(.+) .php?id=&artName= [QSA,L,NC]

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

This will disable multiple choice option.

Summary
Requests to documents sometimes cannot be served by the core apache server because the request was misspelled or miscapitalized. This module addresses this problem by trying to find a matching document, even after all other modules gave up. It does its work by comparing each document name in the requested directory against the requested document name without regard to case, and allowing up to one misspelling (character insertion / omission / transposition or wrong character). A list is built with all document names which were matched using this strategy.