【问题标题】:htaccess rewrite rule with single parameterhtaccess 单参数重写规则
【发布时间】:2023-04-02 10:46:01
【问题描述】:

当用户输入网址时

http://example.com/app/abcd123/

我想显示他的页面

http://example.com/app/index.php?param=abcd123

无需更改浏览器中的 URL。

我把 .htaccess 文件放在 app 文件夹中,里面有代码

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/index.php [NC]
RewriteCond %{QUERY_STRING} ^param=(.*)
RewriteRule (.*) http://example.com/app/%1? [R=301,L]

【问题讨论】:

  • /app/ 是一个真实的目录吗?
  • 是的,我把我的 htaccess 文件放在那里

标签: regex apache .htaccess redirect mod-rewrite


【解决方案1】:

您可以在/app/.htaccess使用此代码:

RewriteEngine on
RewriteBase /app/

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

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

【讨论】:

  • 哇双方重定向(外部到内部和内部到外部),这是一个很好的解决方案,感谢分享先生的欢呼。
【解决方案2】:

试试这个.htaccess 代码。它应该可以帮助你。

确保重写基础应该是您当前目录的根目录。

RewriteBase /app/

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php?param=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php [QSA,NC,L] 

在这种情况下,如果用户输入http://example.com/app/qwerty,则调用将被处理为http://example.com/app/index.php?params=qwerty

这应该可以工作,我测试过。如果您遇到任何麻烦,请告诉我。

【讨论】:

  • 谢谢 - 代码有效,我面临的唯一问题是我的字体停止加载,因为它们也在这个文件夹中并且有类似“/app/fonts/font.ttf?ver=”的链接1.4.4"
  • @moonvader,anubhava 的答案非常适合您的情况。
【解决方案3】:
RewriteEngine On
RewriteBase /app
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php?param=$1 [L]

在那里查看:http://htaccess.mwl.be/ 或其他在线 htaccess 测试服务

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多