php - PHP 重写 URL htaccess 多个条件
问题描述
我正在尝试重写 URL 地址,但我没有取得太大进展。我读了很多书并尝试了,但我没有设法做我想做的事。如果有人给出一个想法,我会很高兴。我想做的是:
- 删除“ .php ”扩展名,例如。“ site.com/about ”
- 如果我输入“ site.com/index.php ”或“ site.com/index ”重定向到“ site.com ”
- 如果我键入“ site.com/profile.php?profile=alex ”以将 URL 重写为“ site.com/profile/alex ”
还要保留我包含的文件的路径,例如 css、js、图像或 php。
我分别尝试过的:
1.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
2.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
3.
RewriteEngine On
RewriteRule ^profile/(.+)[/]?$ profile.php?profile=$1
解决方案
您可以在站点根目录 .htaccess 中有这些规则:
Options -MultiViews
RewriteEngine On
# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+profile\.php\?profile=([^\s&]+)\s [NC]
RewriteRule ^ /%1? [R=302,L,NE]
# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))\.php[\s?] [NC]
RewriteRule ^ /%1%2 [R=301,L,NE]
# To internally forward /dir/file to /dir/file.php
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ profile.php?profile=$1 [L,QSA]
推荐阅读
- node.js - 登录成功后如何自动设置csrf token?
- firebase - Flutter 应用程序无法使用 firebase 登录
- python - 我应该怎么做才能找到最后一次出现的字符串?
- javascript - 在 ReactJs 中加载更多实现
- c# - 仅当使用 linq QueryableExpression 在 c# 中对数据库进行异步调用时才获取 ArgumentException
- sql - 加入具有日期范围的表
- python - 使用正则表达式匹配一列中的模式并根据列属性名称创建一个新列
- unity3d - 如何修复:“GameObject”类型的对象已被破坏,但您仍在尝试访问它?-统一
- f# - 如何使用 Elmish 调试器解决编码器问题?
- javascript - 具有不同 ID 的第二个模态以不同的效果打开 - 为什么?