apache - 将 URL 从复数改写为单数
问题描述
如何将所有复数且后跟的 URL/<integer>
重定向到单数名称以及整数作为参数。请参阅下面的示例。理想情况下,“用户”不需要硬编码,“供应商”将以同样的方式重定向到“供应商”。请注意,我没有使用任何服务器代码(即 PHP 等)。
users.html(不是这个页面是复数)
<a href="/users/1">John Doe</a> <!-- should redirect to user.html?id=1 -->
<a href="/users/2">Jan Doe</a> <!-- should redirect to user.html?id=2 -->
<a href="/users/3">Baby Doe</a> <!-- should redirect to user.html?id=3 -->
当前配置如下。
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName admin.facdocs.example.net
DocumentRoot /var/www/facdocs/frontends/admin/public
<Directory "/var/www/facdocs/frontends/admin/public">
#Options Indexes FollowSymLinks MultiViews
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
allow from all
RewriteEngine On
LogLevel info rewrite:trace3
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z]+)s/(\d+)/?$ $1.html?id=$2 [L]
RewriteBase /
RewriteCond %{REQUEST_URI} !^.*\.html$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ %{REQUEST_FILENAME}.html
</Directory>
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/api.example.net/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/api.example.net/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/api.example.net/chain.pem
</VirtualHost>
</IfModule>
解决方案
要仅将复数作为以结尾的单词处理s
并且仅当.html
存在对应的单词时,您可以匹配为:
RewriteEngine On
# The actual file does not exist already as a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Alpha excluding final `s` captures in $1
# Numeric value in $2 with optional trailing slash
RewriteRule ^([A-Za-z]+)s/(\d+)/?$ $1.html?id=$2 [L]
s
没有对应单数的复数词(以 结尾).html
将导致 404。
注意:以上假设 a <Directory>
or.htaccess
上下文。如果你把它放在服务器级 or<Location>
中,请使用前导斜杠
RewriteRule ^/([A-Za-z]+)s...
这也假设输入的复数和对应的 之间区分大小写.html
。
推荐阅读
- bash - 如何在 bash 中扩展字符串中的范围?
- java - 程序让用户输入数字直到输入零,然后打印总数、输入数和平均值
- android - 资源是在项目外部定义的,无法更新
- mysql - 我对 LeetCode SQL 问题 No.1174 的解决方案。具有 CTE 和窗口功能的即时送餐 II 始终显示语法错误
- python - “激活”不是 conda 命令 - CommandNotFoundError
- swift - SwiftUI 将值从几何阅读器传递给函数
- perl - Perl FileSelect:设置窗口位置
- sql - 将子字符串数字从 nvarchar 转换为数字
- typescript - ESLint 不报告 TypeScript 编译器类型检查错误
- reactjs - 用 Jest/Enzyme 测试延迟的自定义 React 钩子?