【问题标题】:Replace ?id= and .php from url via htaccess in php通过 php 中的 htaccess 从 url 替换 ?id= 和 .php
【发布时间】:2020-10-02 15:19:18
【问题描述】:

我想在我的帖子网址中用斜杠 / 替换 ?id= 和 .php。

我尝试了许多其他问题的答案,但没有像这个一样适合我 -

https://webmasters.stackexchange.com/questions/56411/remove-php-and-id-from-url-and-replace-with-slash/79438

Example Url - 
https://example.com/testing/events/news/post.php?id=13/Checking-to-see-if-this-works

我希望这个示例网址是这样的

https://example.com/testing/events/news/post/13/Checking-to-see-if-this-works

我使用了以下 htaccess 代码,它从 url 中删除了 .php 扩展名,但不知道如何将 ?id= 替换为 /

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

输出 -

https://example.com/testing/events/news/post?id=13/Checking-to-see-if-this-works

我仍然无法将 ?id= 替换为 /

感谢您的帮助:)

【问题讨论】:

  • 写下您“从其他问题中尝试了许多答案”并给出一个答案显然不是关注How to Ask 关于研究的情况。为什么你认为它是? (修辞。)
  • philipxy !我可以列出所有答案的链接,但这将是一个很长的列表。 :)
  • “列出所有答案的链接”显然不是关注How to Ask 关于研究的情况。你显然没有注意我的反问或help center。然后你想知道为什么你的问题没有得到很好的接受? (修辞。)

标签: php .htaccess url


【解决方案1】:

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

Options -MultiViews
RewriteEngine On

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

# internal forward from pretty URL to actual one
RewriteRule ^(post)/(.+)/?$ $1.php?id=$2 [L,QSA,NC]

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

【讨论】:

  • 我试过这段代码。 url 更改,但它给出 404 错误。也许 post.php 需要更改一些内容。因为我得到这样的 id - if (isset($_GET['id'])){ $id = $_GET['id']; }
  • 您的 htaccess 文件在哪里?是否在testing/ 目录中?
  • htaccess 位于此处 - /home/username/public_html/testing/events/news/.htaccess
  • 发布完整的 .htaccess。确保您在测试时没有任何其他规则。
  • 它似乎正在工作。我只是在测试更多以确保它不会破坏任何其他页面 url 或创建重复的 url :)
猜你喜欢
  • 1970-01-01
  • 2013-11-03
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2014-08-12
  • 2018-02-03
  • 2011-12-17
相关资源
最近更新 更多