htaccess - 删除 index.php 并保留一个没有密钥的变量

htaccess - remove index.php and keep a variable without key

原来url是以下之一:

if example.com - 什么都不应该做
如果 example.com/index.php - 它应该显示为 example.com 这是我的代码 - 工作正常:

RewriteEngine ON
RewriteRule ^index\.php/?$ https://%{HTTP_HOST}/ [NC,R=301]
RewriteRule ^/?$ index.php [L]

如果 example.com/index.php?c=lorem 它应该显示为 example.com/lorem

在这两种情况下,

lorem 应该可以被 php 访问:

请帮忙

您可以在站点根目录 .htaccess 中使用这些规则:

DirectoryIndex index.php
RewriteEngine On

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

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+index\.php\?c=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ index.php?c= [L,QSA]

能否根据您显示的示例尝试以下操作。 请在测试您的 URL 之前清除您的浏览器缓存。

RewriteEngine ON
##This rule is for handling index.php file in uri.
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^index\.php/?$ / [R=301,NC,L]
   
##This rule is to redirect from index.php?c=lorem to lorem in uri.
RewriteCond %{THE_REQUEST} index\.php\?c=(lorem)\s [NC]
RewriteRule ^ http://%{HTTP_HOST}/%1? [R=301,L,NE]

##Rule for non-existing files/directories to index.php with variables.
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?c= [L]


OR: 以上是专门针对 lorem 如果您的查询字符串可能是任何内容,请尝试以下操作。

RewriteEngine ON
##This rule is for handling index.php file in uri.
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^index\.php/?$ / [R=301,NC,L]
   
##This rule is to redirect from index.php?c=lorem to lorem in uri.
RewriteCond %{THE_REQUEST} index\.php\?c=([^\s&]*) [NC]
RewriteRule ^ http://%{HTTP_HOST}/%1? [R=301,L,NE]

##Rule for non-existing files/directories to index.php with variables.
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?c= [L]