将我的url重写为动态url


Rewrite my url to a dynamic one

我有一个类似的url

  • https://www.example.com/profile.php?id=1064

我需要将此url更改为

  • https://www.example.com/USERNAME.

此用户名是从数据库中动态获取的,条目id=1064

请建议我一个解决方案,将我的url重写为以上格式

您可以在.htaccess文件中使用RewriteEngine on来添加RewriteRule s。查看Mod Rewrite:

http://httpd.apache.org/docs/current/mod/mod_rewrite.html

首先,您必须在.htaccess内部打开RewriteEngine。

RewriteEngine On

之后,您需要链接的正则表达式。假设您的所有用户名只包含字母和数字,这将是合适的正则表达式。但是,如果不是这样,只需将[A-z0-9]部分调整为您的用户名可以包含的任何字符即可。

RewriteRule ^([A-z0-9])/?$ profile.php?username=$1 [NC,L]

请注意,我们将用户名作为$_GET参数而不是id传递。

此外,建议在链接中的用户名之前加上一些内容。换句话说,http://example.com/u/username而不是http://example.com/username因为如果你有这样的页面http://example.com/random,它将调用以random为用户名的profile.php。因此,对于上面的例子,正则表达式是:

RewriteRule ^u/([A-z0-9])/?$ profile.php?username=$1 [NC,L]