.htaccess code to protect a single URL?

2019-07-30 12:06发布

Is it possible to protect a single URL through .htaccess? For example I will have website.com/index.php?skin=name. Can I password protect only this url? (with no PHP changes, only .htaccess)

website.com/index.php or website.com/index.php?skin=other_name should not be restricted.

标签: .htaccess url
3条回答
太酷不给撩
2楼-- · 2019-07-30 12:12

You can if you use mod-rewrite to rewrite the address to something else and protect that.

https://serverfault.com/questions/94964/apache-locationmatch-directive

You can't use LocationMatch, even though it would appear that you could.

查看更多
在下西门庆
3楼-- · 2019-07-30 12:16

Your best bet is to do it in PHP. A quick google search later and I found a great way to use PHP_AUTH which looks a lot like the .HTACCESS login prompt

<?php
$login_successful = false;

// check user & pwd:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){

    $usr = $_SERVER['PHP_AUTH_USER'];
    $pwd = $_SERVER['PHP_AUTH_PW'];

    if ($usr == 'jonas' && $pwd == 'secret'){
        $login_successful = true;
    }
}

// login ok?
if (!$login_successful){

    // send 401 headers:
    // realm="something" will be shown in the login box 
    header('WWW-Authenticate: Basic realm="Secret page"');
    header('HTTP/1.0 401 Unauthorized');
    print "Login failed!\n";

}
else {
    // show secret page:
    print 'you reached the secret page!';
}

Source: http://snippets.dzone.com/posts/show/2006

查看更多
聊天终结者
4楼-- · 2019-07-30 12:32

You can rewrite the address to protect it like this:

RewriteEngine On
RewriteCond %{REQUEST_URI}  ^/index\.php$
RewriteCond %{QUERY_STRING} ^skin=(name)$
RewriteRule ^(.*)$ /skin/%1 [PT]

<LocationMatch "/skin/name">
     AuthType Basic
     AuthName "By Invitation Only"
     AuthUserFile /path/to/passwords
     Require valid-user
</LocationMatch>
查看更多
登录 后发表回答