带有 URL 重写的 htAccess 不起作用


htaccess with url rewriting not working

这是我的htaccess代码:

RewriteEngine On
RewriteRule ^/typo3$ - [L] RewriteRule ^/typo3/.*$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* /index.php
RewriteRule ^/([a-zA-Z0-9_-]+)$ http://www.example.com/index.php?id=82&user=$1 [L,R=301]

显然我想要这个网址:www.example.com/username将翻译成 http://www.example.com/index.php?id=82&user=username

但是,这不起作用。(此代码导致 htAccess 根本无法正常工作,并出现"找不到页面"错误。

如果我将 ]+$ 更改为 ]+?代码确实有效,但不像我想要的那样:

RewriteEngine On
RewriteRule ^/typo3$ - [L] RewriteRule ^/typo3/.*$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* /index.php
RewriteRule ^/([a-zA-Z0-9_-]+)? http://www.example.com/index.php?id=82&user=$1 [L,R=301]

导致 URL 被重写/重定向到 http://www.example.com/index.php?id=82&user=index ...完全一样,所以用户=索引。

现在,如果我删除重写规则 .*/index.php 行,htaccess 再次根本无法正常工作,导致页面未找到错误......

我花了好几天的时间弄清楚这一点,但我完全一无所知。

所以,我只想 www.example.com/username 重定向到 http://www.example.com/index.php?id=82&user=username

这里有几个问题。

  • 在 .htaccess 文件中,模式"在删除前缀后与文件系统路径"匹配。这意味着,您将没有像/typo3^/([a-zA-Z0-9_-]+)?那样的前导斜杠
  • 模式([a-zA-Z0-9_-]+)?也匹配空请求,因为尾随?。我想,这不是你的意图。
  • 规则按顺序处理,除非您执行重定向[R]或添加[L]标志。这就是为什么首先将请求重写为index.php然后在下一个规则中index被识别为用户并再次重写为.../index.php?id=82&user=index
  • 这导致了模式.*([a-zA-Z0-9_-]+)之间的下一个问题。 .*识别所有请求,包括每个用户。因此,无法区分用户和任何其他请求。

要重写用户名,您可以尝试

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+) http://www.example.com/index.php?id=82&user=$1 [L]

这意味着,如果请求与现有文件!-f或目录!-d不对应,则假定它是一个用户名并重写为index.php?...

如果您不想重定向,请省略主机名

RewriteRule ^([a-zA-Z0-9_-]+) /index.php?id=82&user=$1 [L]