【问题标题】:Remove extension and add get value with traling slash删除扩展名并使用斜杠添加获取值
【发布时间】:2015-12-26 15:39:08
【问题描述】:

要做到这一点:

原始网址 -> localhost/viewprofile.php

重写网址 -> localhost/viewprofile/

我使用了这个代码。

# Apache Rewrite Rules
 <IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On
  RewriteBase /

# Add trailing slash to url
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
  RewriteRule ^(.*)$ $1/ [R=301,L]

# Remove .php-extension from url
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}\.php -f
  RewriteRule ^([^\.]+)/$ $1.php 

# End of Apache Rewrite Rules
 </IfModule>

现在我用了

原始网址 -> localhost/viewprofile.php?user_id = 1

重写网址 -> localhost/1/

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ viewprofile.php?user_id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ viewprofile.php?user_id=$1

但不幸的是我想这样做

原始网址 -> localhost/viewprofile.php?user_id = 1

重写网址 -> localhost/viewprofile/1/

还有这个

原始网址 -> localhost/viewprofile.php?username=sean

重写网址 -> localhost/viewprofile/sean/

我有这两个Original URLs,我想将它们分别重写为上面给出的ReWrite URL

任何人有任何解决方案?

【问题讨论】:

  • 请简要说明您的问题,以便其他人理解并相应回答。
  • Original URL 是我所拥有的,ReWrite URL 是我想要实现的。 @PSN

标签: php .htaccess url mod-rewrite url-rewriting


【解决方案1】:

您可以匹配第一个数字(仅)和另一个字母数字(例如)

<IfModule mod_rewrite.c>
  Options +FollowSymLinks -MultiViews
  RewriteEngine On
  RewriteBase /

  # Add trailing slash to url
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
  RewriteRule ^(.+)$ $1/ [R=301,L]

  # Remove .php-extension from url
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
  RewriteRule ^(.+)/$ $1.php [L]

  RewriteRule ^viewprofile/([0-9]+)/?$ viewprofile.php?user_id=$1 [L]
  RewriteRule ^viewprofile/([A-Za-z0-9]+)/?$ viewprofile.php?username=$1 [L]
</IfModule>

【讨论】:

  • 不,当我尝试localhost/viewprofile/1/它的 404 时不起作用
  • 您是否使用了我上面提供给您的代码?因为您的初始代码中存在一些语法错误和缺失部分。另外,您的 htaccess 在哪里?在根文件夹中?还是在viewprofile 文件夹中(如果它是物理文件夹)?
  • 是的,我复制了。它在root 文件夹中并且没有像viewprofile 这样的文件夹,它只是一个.php 文件
  • 好吧,你是对的,我没有测试它,我的错。我修改了RewriteCond,现在可以使用了
猜你喜欢
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 2012-04-15
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多