wordpress htaccess如何删除除index.php之外的所有php扩展

标签 wordpress apache .htaccess url-rewriting

我有一个 WordPress 博客,我想在其中添加一些自定义页面,并从网址中删除 .php 扩展名和查询字符串。

所有 WordPress 页面网址都类似于 index.php?pagename=,因此如果我尝试在 中添加 RewriteRule ^(.*)$ $1.php .htaccess 文件,其他页面返回500 内部服务器错误。如何从除 index.phplogin.php 之外的所有内容中删除 php 扩展?

这是我现有的 .htaccess 文件:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# RewriteRule ^(.*)$ $1.php  # add this line will broken the wordpress rewrite rule
</IfModule>
# END WordPress

最佳答案

例如,如果您想添加一些自定义 php 页面,您应该在标准 WordPress 部分之前添加您自己的重写,但在 RewriteBase / 之后。

在这里,我添加了一些重写,能够处理存储在私有(private)目录 custom 中的自定义页面。 .

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # *** START CUSTOM PART ***
    RewriteRule ^page1$     /custom/page1.php    [L,QSA]
    RewriteRule ^page2$     /custom/page2.php    [L,QSA]
    # *** END CUSTOM PART ***

    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    # END WordPress

如果您的网站在 http://www.example.com 上可用,您的自定义页面将可以使用 http://www.example.com/page1 访问, http://www.example.com/page2等等...

关于重写标志的几句话[L,QSA] :

  • L - 如果重写匹配,则立即停止重写过程,并且不再应用任何规则。
  • QSA - 将原始请求 URL 中的任何查询字符串附加到自定义页面。意思是调用http://www.example.com/page1?foo=bar&c=1将被内部重写为/custom/page1.php?foo=bar&c=1

请注意:

  1. 如果您的 WordPress 站点中已有名为“page1”的页面,则此页面将被添加到重写规则中的自定义页面覆盖。
  2. 这些 Apache httpd 指令是标准的,由 Wordpress 生成,配置 Permalink Settings 。我刚刚添加了自定义部分。
  3. 任何时候改变Permalink Settings ,你的.htaccess会被覆盖,如果你改变的话更好 .htaccess使文件只读的权限。并且,无论如何,请保存 .htaccess 配置的副本。

另一方面,如果您只希望 WordPress 的 URL 更适合 SEO,即没有 .php 的 URL页面,没有完整的查询字符串,只有帖子/页面slug作为唯一标识符,您可以访问 Wordpress Permalink Settings并选择Post name或您喜欢的选项:

Wordpress permalink settings

当您激活Permalink Settings时,Apache httpd 的工作仅限于 .htaccess 部分。这意味着 Apache 通过 .htaccess 将所有内容(请求 header 和正文)重定向到 index.php 页面,并且 Wordpress 在内部实现每次重写。 如果您需要更多有关 WordPress 配置的建议,我建议您将问题写在 https://wordpress.stackexchange.com/

关于wordpress htaccess如何删除除index.php之外的所有php扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425881/

相关文章:

database - 用于登录的 Wordpress 共享用户数据库

php - LAMP 服务器是否可以在需要时更改其 IP?

php - 除非首字母大写,否则 Mod_rewrite 不适用于某些规则? HTTPS服务器

android - htaccess 针对代理的保护

php - 直接从 codeigniter 的 application\view 文件夹访问特定文件夹/文件

html - 我可以让这个字体有一个线宽,以便它在下一行继续吗?

css - wordpress 菜单描述 css 错误-无法对齐

javascript - 如何使用 Javascript 和 PHP 启用鼠标滚轮水平滚动

apache - 添加、删除或重新加载特定虚拟主机,无需重新启动 Apache(并中断其他 VirtualHost 的请求)

php - 如何使用 xampp 安装 ffmpeg