首页 > 解决方案 > 将 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>

标签: apache.htaccessmod-rewriteurl-rewritingfriendly-url

解决方案


要仅将复数作为以结尾的单词处理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


推荐阅读