【问题标题】:PHP rewrite URL htaccess multiple conditionsPHP 重写 URL htaccess 多个条件
【发布时间】:2019-03-31 22:30:47
【问题描述】:

我正在尝试重写 URL 地址,但没有取得太大进展。 我读了很多书并尝试了,但我没有设法做我想做的事。如果有人给出一个想法,我会很高兴。 我想做的是:

  1. 删除“.php”扩展名,例如。 “site.com/about
  2. 如果我输入“site.com/index.php”或“site.com/index”到 重定向到“site.com
  3. 如果我键入“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

【问题讨论】:

  • 为什么不重写所有对 index.php 的请求并使用router
  • 嗨@Jaquarh 感谢您的建议,但代码大部分是内联的。
  • @anubhava 是的,对于 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.RewriteRule ^profile/(.+)[/]?$ profile.php?profile=$1
  • 请编辑您的问题显示您尝试的 .htaccess

标签: php .htaccess url url-rewriting


【解决方案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]

【讨论】:

  • 是的,它可以工作,除非我在 site.com/profile/alex 上的 css、js、图像和 url 路径是错误的。尝试从 site.com/profile/aboutsite.com/profile/css/style.css 等加载它们。
  • 对于 css/js 问题,您可以在页面 HTML 的 <head> 标签下方添加:<base href="/" />
  • 非常感谢,完美运行。上帝祝福你。最后一个纯粹好奇的问题。是否有一个选项代替 site.com/profile/alexsite.com/alex
  • 你好,如果可能的话,我想问你一些别的问题。我有动态加载内容的类别(AJAX)。类别是静态的,不会改变,它们是 3(电影、书籍和卡片)。如果我键入 site.com/movies 以将我重定向到带有类别的索引页面,我会尝试这样做,这样我就可以获取参数并通过 AJAX 提交,然后加载内容。是否可以将这些类别添加到 htaccess 文件中,如果输入,是否可以重定向到 index/category(site.com/movies)?这会与配置文件的其他条件产生冲突吗?我很高兴听到你的建议。谢谢。
  • 您可以拥有类似/category/abcd 的URI,并将其重写为类似/index.php?cat=abcd 的内容。该规则应放在# internal forward 行之前。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多