【问题标题】:Password protect specific pretty URLs in .htaccess密码保护 .htaccess 中的特定漂亮 URL
【发布时间】:2016-03-07 13:51:54
【问题描述】:

我需要通过.htpasswd.htaccess 中的许多漂亮URL 进行密码保护。但我希望为许多受保护的漂亮 URL 中的每一个提供不同的用户/登录名(以及未特别受保护的页面的一般登录名)。

所以,例如,我想保护:

使用特定的用户/密码:

http://www.example.com/pretty/url

使用另一个用户/密码:

http://www.example.com/pretty/link

使用通用用户/密码(所有其他)

http://www.example.com/pretty/generic
http://www.example.com/pretty/all
http://www.example.com/pretty/

我尝试使用来自this answer 的代码,我发现它最适合我的需求:

# Do the regex check against the URI here, if match, set the "require_auth" var
SetEnvIf Request_URI ^/pretty/url require_auth=true

# Auth stuff
AuthUserFile /var/www/htpasswd
AuthName "Password Protected"
AuthType Basic

# Setup a deny/allow
Order Deny,Allow
# Deny from everyone
Deny from all
# except if either of these are satisfied
Satisfy any
# 1. a valid authenticated user
Require valid-user
# or 2. the "require_auth" var is NOT set
Allow from env=!require_auth

它与一个漂亮的 URL 配合得很好。但是我无法找到一种方法来适应许多 URL,每个 URL 都有不同的用户,通过 htpasswd

【问题讨论】:

  • 感觉好像通过代码中的某种授权来处理这个问题要容易得多。您将能够建立一个更灵活、更易于管理的系统。
  • 这不是您正在寻找的解决方案,但它可能是解决问题的方法:您是否可以选择根据存储在 . htpasswd?
  • 不幸的是没有@Pheagey,这些是没有关联物理路径的漂亮 URL
  • 同意@purpleninja,但现在代码有点不灵活
  • @JoãoPauloApolinárioPassos 您不能通过 apache 使用基本 HTTP 身份验证来执行此操作,因为它需要保护物理路径。

标签: apache .htaccess .htpasswd


【解决方案1】:

只需通过 php 发送身份验证标头即可弹出身份验证窗口。在您的代码中,您可以检查不同的用户并请求 uri。在此示例中,它仅检查用户,但您也可以比较 REQUEST_URI 或 PARAMS。它应该只向您展示概念。

<?php
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header("WWW-Authenticate: Basic realm=\"Private Area\"");
        header("HTTP/1.0 401 Unauthorized");
        print "Sorry - you need valid credentials to be granted access!\n";
        exit;
    } else {
        if (preg_match('/^\/pretty\/url/', $_SERVER["REQUEST_URI"], $matches) && $_SERVER['PHP_AUTH_USER'] == 'paul') {
            print "Welcome to the private area!";
        } else {
            header("WWW-Authenticate: Basic realm=\"Private Area\"");
            header("HTTP/1.0 401 Unauthorized");
            print "Sorry - you need valid credentials to be granted access!\n";
            exit;
        }
    }
?>

【讨论】:

  • 我不能那样操作我的代码,这就是为什么我现在需要一个纯 .htaccess 解决方案
  • @JoãoPauloApolinárioPassos 好的,那为什么用 php 标记它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
  • 2014-05-07
  • 1970-01-01
  • 2020-09-09
  • 2014-09-24
相关资源
最近更新 更多