【问题标题】:URL forwarding with two arguments带有两个参数的 URL 转发
【发布时间】:2012-12-05 07:35:34
【问题描述】:

这是我当前的 .htaccess

   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^([0-9a-zA-Z-]+)/?$ index.php?u=$1 [L]
   RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
   RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

它将 www.example.com 变成 example.com 并将 example.com/username 解释为 example.com/ index.php?u=用户名

现在我想传递第二个参数,如 example.com/index.php?u=username&e=email 并仍然保持格式 example.com/arg1&arg2。如何在 .htaccess 中执行此操作?

【问题讨论】:

    标签: apache .htaccess url web lamp


    【解决方案1】:

    首先,您需要将重定向移至您的路由规则:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    

    然后,您要检查 2 参数路由:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([0-9a-zA-Z-]+)/([^/]+)/?$ /index.php?u=$1&e=$2 [L,QSA]
    

    (假设 URL 看起来像:http://example.com/username/emailaddress,但如果您真的希望 & 将它们分开,请改用此规则:

    RewriteRule ^([0-9a-zA-Z-]+)&([^/]+)/?$ /index.php?u=$1&e=$2 [L,QSA]
    

    这假定 URL 看起来像:http://example.com/username&emailaddress

    现在你原来的规则:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([0-9a-zA-Z-]+)/?$ /index.php?u=$1 [L,QSA]
    

    【讨论】:

    • 这在我传递两个参数时有效。当我只通过一个 arg 时,如何使其通用?
    • @LeonardoDaVintik 如果它根据您的问题有效,您应该首先考虑accepting 的答案。
    • @LeonardoDaVintik “我只通过一个 arg 的情况下通用”是什么意思?您最初拥有的规则负责处理 1 参数情况。上面的,2个参数请求,顶部是重定向。
    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 2015-10-24
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2015-10-30
    • 2021-08-18
    相关资源
    最近更新 更多