.htaccess to secure admin directory in mvc architecture - .htaccess

I am trying to make a site with mvc structure. I have this :
www/
blog/
app/
admin/
controller/
model/
view/
config/
front/
controller/
model/
view/
assets/
images/
libs/
portfolio /
I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]
The file index.php in www/blog/ parses the url and uses the right controllers like this :
//****************************************************
include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();
include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();
if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
$lapage=explode('/',$_GET['p']);
if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}
if (!isset($pp) OR $pp == 'index')
{
$ctrl = "home"; $p = $ctrl;
} else {
$params = explode('/',$pp);
$ctrl = $params[0]; $p = $ctrl;
if (isset($params[1])) {
if ($params[1]<>"") {$p = $params[1];}
}
}
$c=$controlB->load($ctrl);
include_once($c);
}else{
//on est en front
if (!isset($_GET['p']) OR $_GET['p'] == 'index')
{
$ctrl = "home"; $p = $ctrl;
} else {
$params = explode('/',$_GET['p']);
$ctrl = $params[0]; $p = $ctrl;
if (isset($params[1])) {
if ($params[1]<>"") {$p = $params[1];}
}
}
$c=$controlF->load($ctrl);
include_once($c);
}
//****************************************************
Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :
<Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>

The Directory directive can only be used in server configuration or virtual host files. It cannot be used in htaccess files. It is described in Apache Directory Directive.
To password protect a directory using htaccess, you have to enter the following in .htaccess file:
AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
Require user rbowen
The above commands will password protect the folder containing the htaccess file. The command: htpasswd -c /usr/local/apache/passwd/passwords rbowen generates a password for the user rbowen. It is described in Apache Authentication and Authorization

I find a way : use sessions with php
http://www.apprendre-php.com/tutoriels/tutoriel-14-les-sessions.html

Related

.htaccess Pretty URL with languages

I have a php website, loading the pages as below.
if ( $secretfile && file_exists( $moddir . $name . "/" . $secretfile . ".php" ) ) {
include_once( $moddir . $name . "/" . $secretfile . ".php" );
} else {
if ( isset( $_GET[ 'mod' ] ) ? $_GET[ 'mod' ] : '' ) {
$secretmodule = isset( $_GET[ 'mod' ] ) ? $_GET[ 'mod' ] : '';
if ( $secretmodule && file_exists( $moddir . $name . "/page.php" ) ) {
include_once( $moddir . $name . "/page.php" );
} else {
include_once( $moddir . "404.php" );
}
} else {
include_once( $moddir . "homepage.php" );
}
}
I am using htaccess to beautify the url as below.
RewriteRule ^([^/]*)/$ /index.php?mod=$1 [L]
RewriteRule ^([^/]*)/([^/]*)/$ /index.php?mod=$1&file=$2 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/$ /index.php?mod=$1&file=$2&proid=$3 [L]
I want to add languages in session but i dont want to change the url of the main language (already indexed). only the other languages will be added an extra variable.
eg:
main language(de) : www.site.com/module/file/ /index.php?mod=$1&file=$2 [L]
other lang (en) : www.site.com/en/module/file/ /index.php?lang=$1mod=$2&file=$3 [L]
other lang (fr) : www.site.com/fr/module/file/ /index.php?lang=$1mod=$2&file=$3 [L]
I am just not sure how to setup the htaccess for these configurations.
You can have these set of rules in .htaccess:
RewriteEngine On
# ignore all files are directories from rules below
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# rules with any lang component
RewriteRule ^(en|fr)/([^/]*)/$ index.php?lang=$1&mod=$2 [L,QSA]
RewriteRule ^(en|fr)/([^/]*)/([^/]*)/$ index.php?lang=$1&mod=$2&file=$3 [L,QSA]
RewriteRule ^(en|fr)/([^/]*)/([^/]*)/([^/]*)/$ index.php?lang=$1&mod=$2&file=$3&proid=$4 [L,QSA]
# rules without any lang component
RewriteRule ^([^/]*)/$ index.php?lang=de&mod=$1 [L,QSA]
RewriteRule ^([^/]*)/([^/]*)/$ index.php?lang=de&mod=$1&file=$2 [L,QSA]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/$ index.php?lang=de&mod=$1&file=$2&proid=$3 [L,QSA]
With your shown attempts, please try following. Make sure your index.php file and htaccess both files are present in same folder(root) in your case.
Please make sure to clear your browser cache before testing your URLs.
RewriteEngine ON
##Rules for en OR fr languages URLs to be rewritten in backend.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(en|fr)/([^/]*)/([^/]*)/?$ /index.php?lang=$1mod=$2&file=$3 [QSA,NC,L]
##Rules for links which are not started with en OR fr links.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/?$ /index.php?lang=$1mod=$2&file=$3 [QSA,NC,L]

CakePHP Images in webroot not displaying in Production

I have pushed my website to Production yesterday, all is working fine with the 3 .htaccess files I created. The only issue is that the images from my webroot folder are not displayed.
I am calling them with $this->Url->image('pages/' . $page->image)
Link rendered in html :
background-image:url(/app/img/pages/home.jpg);
'App' => [
'namespace' => 'App',
'encoding' => env('APP_ENCODING', 'UTF-8'),
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'fr_FR'),
'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'Europe/Brussels'),
'base' => false,
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
//'baseUrl' => env('SCRIPT_NAME'),
'fullBaseUrl' => false,
'imageBaseUrl' => 'img/',
'cssBaseUrl' => 'css/',
'jsBaseUrl' => 'js/',
'paths' => [
'plugins' => [ROOT . DS . 'plugins' . DS],
'templates' => [ROOT . DS . 'templates' . DS],
'locales' => [RESOURCES . 'locales' . DS],
],
],
/var/htdocs/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]
</IfModule>
/app/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]
</IfModule>
/app/webroot/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Thank you.
Here is my error Log
2021-10-21 13:18:34 Error: [Cake\Http\Exception\MissingControllerException] Controller class Img could not be found. in /homepages/20/d887310999/htdocs/app/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php on line 226
Stack Trace:
/homepages/20/d887310999/htdocs/app/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php:65
/homepages/20/d887310999/htdocs/app/vendor/cakephp/cakephp/src/Http/BaseApplication.php:311
Request URL: /img/pages/home.jpg

How to configure the .htaccess file for ErrorDocument working?

Good day! I'm doing the website on PHP. It will be a static site with limited count of pages. These pages have idential styles and scripts, so I wrote the viewpage.php script, which get the page name by URL and show it by PHP instruction include if such page is setted or put error 404 otherwise.
It is a structure of my website files:
admin/
auth.php
exit.php
index.php
pages/
index.php
contacts.php
...
err/
err404.php
.htaccess
viewpage.php
and part of viewpage.php
$pages = [
"index/" => [
"page" => "index.php"
],
"contacts/" => [
"page" => "contacts.php"
],
];
...
$requestPage = $_GET[ "page" ] . "/";
if ( !array_key_exists( $requestPage, $pages ) ) {
http_response_code( 404 );
include "pages/err/err404.php";
exit();
}
...
include "pages/$pageFile"; ?>
I want to allow the direct access to site/admin/[index|auth|exit].php and get such redirections:
site/admin/ => site/admin/index.php
site/ => site/viewpage.php?page=index
site/contacts => site/viewpage.php?page=contacts
site/contacts/ => site/viewpage.php?page=contacts
otherwise => site/pages/err/err404.php
I have tried this variant of .htaccess:
ErrorDocument 404 /pages/err/err404.php
RewriteEngine On
RewriteRule ^admin$ admin/index.php [L]
RewriteRule ^admin/$ admin/index.php [L]
RewriteRule ^([a-z\-]+)$ viewpage.php?page=$1 [L]
RewriteRule ^([a-z\-]+)/$ viewpage.php?page=$1 [L]
but I have problems: I can't open main page by site/, only by site/index/
How me to configure the .htaccess file?

MAMP Htaccess password protection: "Authentication required" dialog being repeated

I'm running MAMP 3.2.2 on Windows 10, with Apache on port 8888. I'm trying to password protect the directory C:\MAMP\htdocs\admin\ by placing a .htaccess and a .htpasswd files inside it.
.htacess is:
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile C:\MAMP\htdocs\admin\.htpasswd
Require valid-user
.htpasswd (user = test; password = test) is:
test:dGRkPurkuWmW2
I checked MAMP's Apache httpd.conf and it says, in line 202:
<Directory />
Options FollowSymLinks ExecCGI
AllowOverride All
Order deny,allow
Allow from all
</Directory>
And, in line 220:
<Directory "C:\MAMP\htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks ExecCGI
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
When trying to navigate to "http://localhost:8888/admin/index.php" I get the "Authentication Required" dialog, saying that "http://localhost:8888 is requesting your username and password". But, after entering username and password, the dialog keeps reappearing, instead of granting me access.
What am I missing?
Thank you in advance!
The password test:dGRkPurkuWmW2 is wrong. Check the log files (\mamp\apache\logs\error.log) to see the error messages, there should be something like this:
[Sat Dec 10 10:39:04.965830 2016] [auth_basic:error] [pid 2200:tid 1648] [client ::1:49487] AH01617: user test: authentication failure for "/protected/": Password Mismatch
Use this HTPasswd Generator form to generate a valid password, which in your case for user test and password test will be something like this, but it always produces something different:
test:$apr1$2pi0lu5b$Omg8StTZWO0m5lMfq/D8d.
Here is a screen capture with my working example using the password above:
UPDATE
Note that this algorithm is working for Windows. The password you have at your code ($encryptedPassword = crypt($typedPassword, base64_encode($typedPassword));) works on Linux based systems and it is the default algorithm used by Apache 2.2.17 and older. From Apache 2.2.18, the default encryption method is based on MD5 and it can be used on both Windows and Linux based systems. You can read more about it here How to generate passwords for .htpasswd using PHP.
PHP code with the function crypt_apr1_md5 to generate a .htpasswd password entry for APR1-MD5 encryption compatible for windows:
<?php
// APR1-MD5 encryption method (windows compatible)
function crypt_apr1_md5($plainpasswd)
{
$salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
$len = strlen($plainpasswd);
$text = $plainpasswd.'$apr1$'.$salt;
$bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
$bin = pack("H32", md5($text));
for($i = 0; $i < 1000; $i++)
{
$new = ($i & 1) ? $plainpasswd : $bin;
if ($i % 3) $new .= $salt;
if ($i % 7) $new .= $plainpasswd;
$new .= ($i & 1) ? $bin : $plainpasswd;
$bin = pack("H32", md5($new));
}
for ($i = 0; $i < 5; $i++)
{
$k = $i + 6;
$j = $i + 12;
if ($j == 16) $j = 5;
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
$tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
// Password to be used for the user
$username = 'test';
$password = 'test';
// Encrypt password
$encrypted_password = crypt_apr1_md5($password);
// Print line to be added to .htpasswd file
echo $username . ':' . $encrypted_password;

how to create htacess to rewrite the route in yii2

I use yii2 to develop a website, and I use the Virtual host.
The question is in yii2 the source code is put in the web folder, and I have to visit the website like this "http://www.mydoname.com/web/index.php", if I want to visit like "http://www.mydoname.com/index.php" ,how to create the .htaccess in the root, what should I write?
Lets try this:
1- Create .htaccess file on the root directory(yii2-app) with this content
Options -Indexes
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} /(uploads)
RewriteRule ^uploads/(.*)$ uploads/$1 [L]
RewriteRule ^(.*)$ frontend/web/$1 [L]
</IfModule>
# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>
# Deny accessing dot files
RewriteRule (^\.|/\.) - [F]
2- Create .htaccess file in frontend/web with the below contents
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
3- Now, open the frontend/config/main.php file and set $baseUrl for \yii\web\Request and \yii\web\urlManager.
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'baseUrl' => $baseUrl,
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'baseUrl' => $baseUrl,
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => []
]
],
'params' => $params,
];
Visit: localhost/yii2-app/
Original reference

Resources