Rewrite http to https and viceversa with .htaccess - php

I want to rewrite all URL to SSL except specific folders/controllers with Zend Framework. For example, I want to exclude auth controller from SSL, then if I access to https://blabla.com/auth I want to be rewrited to http://blabla.com/auth.
I've tried some code in htaccess https redirect only on specific Zend Frameworks controller/actions and Rewrite all URL to SSL except specific folders with Zend Framework but nothing worked for me.
By now this is the code I've in .htaccess file. Any suggestions?
RewriteEngine On
RewriteCond %{HTTPS} on [NC]
RewriteCond %{REQUEST_URI} !^/(auth|client)/ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} off [NC]
RewriteCond %{REQUEST_URI} ^/(auth|client)/ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [L]
UPDATE
It doesn't throw any errors, but when I access to the page with http it redirects me to the index page with https:
RewriteEngine On
#If HTTPS is off and this is not /auth or /client - redirect to https
RewriteCond %{HTTPS} off
RewriteCond $1 !^(en/x/auth/index) [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
#If HTTPS is off and this is /auth or /client - redirect to http
RewriteCond %{HTTPS} on
RewriteCond $1 ^(en/x/auth/index) [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R,L]
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Don't need to change something in the .htacess just create a plugin controller
Controller plugin
namespace Custom\Controller\Plugin;
class Ssl extends \Zend_Controller_Plugin_Abstract
{
/**
* Check the application.ini file for security settings.
* If the url requires being secured, r ebuild a secure url
* and redirect.
*
* #param Zend_Controller_Request_Abstract $request
* #return void
* #author Travis Boudreaux
*/
public function preDispatch(\Zend_Controller_Request_Abstract $request)
{
$shouldSecureUrl = false;
$options = new \Zend_Config_Ini(APPLICATION_PATH . '/configs/ssl.ini');
$options = $options->ssl;
//if config is empty, exit
if (!is_object($options))
return;
//simpler to use
$options = $options->toArray();
if (APPLICATION_ENV == 'production') {
if ($request->controller == 'ajax')
return;
//check configuration file for one of three require_ssl directives
//secure an entire module with modules.module_name.require_ssl = true
//secure an entire controller with modules.module_name.controller_name.require_ssl = true
//secure an action with modules.module_name.controller_name.action_name.require_ssl = true
if (isset($options['modules'][$request->module][$request->controller]['require_ssl'])
&& ($options['modules'][$request->module][$request->controller]['require_ssl'])
) {
$shouldSecureUrl = true;
} elseif (isset($options['modules'][$request->module][$request->controller][$request->action]['require_ssl'])
&& ($options['modules'][$request->module][$request->controller][$request->action]['require_ssl'])
) {
$shouldSecureUrl = true;
} elseif (isset($options['modules'][$request->module][$request->controller][$request->action]['require_ssl'])
&& !($options['modules'][$request->module][$request->controller][$request->action]['require_ssl'])
) {
$shouldSecureUrl = false;
}
if (empty($shouldSecureUrl))
$shouldSecureUrl = false;
$this->_setupUrls($request, $shouldSecureUrl);
}
}
/**
* Check the request to see if it is secure. If it isn't
* rebuild a secure url, redirect and exit.
*
* #param Zend_Controller_Request_Abstract $request
* #param boolean $secure_url
* #return void
* #author Travis Boudreaux
*/
protected function _setupUrls(\Zend_Controller_Request_Abstract $request, $secure_url)
{
$server = $request->getServer();
$hostname = $server['HTTP_HOST'];
if ($request->isSecure()) {
if (!$secure_url) {
$url = \Zend_Controller_Request_Http::SCHEME_HTTP;
$url .= '://' . $hostname . $request->getRequestUri();
$redirector = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->setGoToUrl($url);
$redirector->redirectAndExit();
}
} else {
if ($secure_url) {
$url = \Zend_Controller_Request_Http::SCHEME_HTTPS;
$url .= '://' . $hostname . $request->getRequestUri();
$redirector = \Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->setGoToUrl($url);
$redirector->redirectAndExit();
}
}
}
}
ssl.ini can be saved in APPLICATION_PATH . '/configs' directory
ssl.modules.default.register.require_ssl = true
ssl.modules.default.login.require_ssl = true
ssl.modules.default.dashboard.require_ssl = true
ssl.modules.default.payment.require_ssl = true
ssl.modules.default.password.require_ssl = true
ssl.modules.default.profile.require_ssl = true
ssl.modules.admin.login.login.require_ssl = true
ssl.modules.admin.dashboard.require_ssl = true
ssl.modules.admin.payment.require_ssl = true
ssl.modules.admin.password.password.require_ssl = true
ssl.modules.admin.password.forgot.require_ssl = true
ssl.modules.admin.publicateur.require_ssl = true
ssl.modules.admin.profile.require_ssl = true
And finally register the plugin in your bootstrap
/* other bootstrap config above */
protected function _initPlugin()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Ssl());
}

I think, you made the conditions wrong. I tried to rewrite:
#If HTTPS is off and this is not /auth or /client - redirect to https
RewriteCond %{HTTPS} off
RewriteCond $1 !^(auth|client) [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
#If HTTPS is off and this is /auth or /client - redirect to http
RewriteCond %{HTTPS} on
RewriteCond $1 ^(auth|client) [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]

Related

Codeigniter 3 index method behaving unexpectedly

I have a CodeIgniter project on a subdomain. Now, When I visit sub.example.com it loads a login page and on successful login, it redirects to dashboard. Once logged in and session are in place visiting sub.example.com/login/ will auto-redirect to the dashboard page. Now here's my problem. After successful login, visiting sub.example.com doesn't redirect anywhere it simply load the login page. But visiting sub.example.com/index.php does redirect me to the dashboard page.
For some reason, my index method is called or working properly.
Here my code.
.htaccess
IndexIgnore *
php_value date.timezone Asia/Kolkata
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
## Remove www from URL
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://sub.example.com/$1 [R=301,L]
## Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^sub.example.com$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
config.php
if ($_SERVER['REMOTE_ADDR'] == "127.0.0.1") {
$config['base_url'] = "http://" . $_SERVER['SERVER_NAME'];
} else {
$config['base_url'] = "https://" . $_SERVER['SERVER_NAME'];
}
routes.php
$route['default_controller'] = 'root';
$route['root_controller'] = 'root';
/*API CONTROLLER*/
$route['api_controller'] = 'api';
/*Guest Controller*/
$route['guest_controller'] = 'guest';
/*Custom Routes*/
$route['dashboard/(:any)'] = 'root/dashboard/$1';
$route['search/(:any)'] = 'root/search/$1';
$route['search/(:any)/(:num)'] = 'root/search/$1/$2';
$route['export/(:any)'] = 'root/export/$1';
root controller
public function __construct()
{
parent::__construct();
$this->default_data = array("project_name" => PROJECT_NAME);
if ($this->router->method == "privacy_policy") {
return;
}
$this->load->library('session');
if ($this->router->method == "login") {
if ($this->session->userdata("username")) {
redirect(base_url("dashboard/"));
}
} else {
if (!$this->session->userdata("username")) {
redirect(base_url("login/"));
}
}
//Set MYSQL timezone
$this->db->query("SET time_zone = '+05:30'");
}
/**
* Dashboard View
*/
public function index()
{
redirect(base_url("/dashboard/"));
}
/**
* Login View
*/
public function login()
{
$data = $this->default_data;
if ($_POST) {
$username = $this->input->post("username");
$plain_password = $this->input->post("password");
$this->load->model("authenticate");
if (!$this->authenticate->auth($username, $plain_password)) {
$data['message'] = "Invalid Credentials";
}
}
$this->load->view('login', $data);
}
Update
Forgot to mention that I am having this issue only on the remote server. On localhost it's working fine.
Hers is an idea - add this after you have loaded the session object:
if ($this->session->userdata("username") && $this->router->method == "index") {
redirect(base_url("dashboard/"));
}
Please use this .htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/system.*
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?/$1 [L]
if you visiting sub.example.com/index.php successfully then try this
public function login()
{
$data = $this->default_data;
if ($_POST) {
$username = $this->input->post("username");
$plain_password = $this->input->post("password");
$this->load->model("authenticate");
if (!$this->authenticate->auth($username, $plain_password)) {
$data['message'] = "Invalid Credentials";
}else{
//go to dashboard function
$this->index();
}
}
$this->load->view('login', $data);
}
Turns out there was some issue with files on the remote server. I don't exactly know if the files were different or corrupted but replacing the whole project on the remote server fixed the issue
"Turns out there was some issue with files on the remote server. I don't exactly know if the files were different or corrupted but replacing the whole project on the remote server fixed the issue" --
#Akash You should compare your local and remote .htaccess files. I think that will explain your problem.

How to write multiple url for diff pages using php and htaccess

I need multiple url rewriting method for my web page.
I am able to work with one url rewriting using PHP and htaccess as:
index.php page code
PHP code:
$retvalue=$_POST["packagestring"];
$_SESSION["package_string"] = $retvalue;
header("location:package/".php_slug($retvalue)."");
}
function php_slug($string)
{
list($packageid, $packagename) = explode(":",$string);
$url = $packageid."/".strtolower(str_replace(' ', '-', $packagename));
$slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($url)));
return $url;
}
When I click on the button, via post method of index page i jump to package page with the url as:
http://localhost/xyz/package/2/temp-temp-temp
as this package page contains one submit button and when i click on this usbmuit button i want to go to book_package page with the below url:
http://localhost/xyz/book_package/2/temp-temp-temp
but I am getting as
http://localhost/xyz/package/2/book_package.php
Here is the working htaccess file with url and not with second url
RewriteEngine On
RewriteRule ^(.+)/(admin|css|fonts|ico|include|js|images)/(.*)$ $1
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^package/([a-zA-Z0-9-/]+)$ package.php?packagestring=$1
RewriteRule ^package/([a-zA-Z-0-9-]+)/ package.php?packagestring=$1
RewriteRule ^xyz/(css|js|img)/(.*)?$ /$1 [L,QSA,R=301]
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^book_package/([a-zA-Z0-9-/]+)$ book_package.php?booknow=$1
RewriteRule ^book_package/([a-zA-Z-0-9-]+)/ book_package.php?booknow=$1
RewriteRule ^xyz/(css|js|img)/(.*)?$ /$1 [L,QSA,R=301]
Below is the code for package page for url rewriting:
if(!isset($_GET["packagestring"])){
header('location:index.php');
}elseif(isset($_GET["packagestring"])) {
$getpackage = $_GET["packagestring"];
}
function php_slug($string)
{
list($packageid, $packagename) = explode(":",$string);
$url = $packageid."/".strtolower(str_replace(' ', '-', $packagename));
$slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($url)));
return $url;
}
if(isset($_POST["booknow"])){
$retvalue=$_POST["booknow"];
var_dump($retvalue);
header("location:book_package.php");
}
Any one suggest me that how to implement this
I have 3 pages as
1. index.php
2. package.php
3. book_package.php and I want to traverse in the order 1->2->3
index page partial code as:
if(isset($_POST["packagestring"])){
$retvalue=$_POST["packagestring"];
$_SESSION["package_string"] = $retvalue;
header("location:package/".php_slug($retvalue)."");
}
function php_slug($string)
{
list($packageid, $packagename) = explode(":",$string);
$url = $packageid."/".strtolower(str_replace(' ', '-', $packagename));
$slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($url)));
return $url;
}
ON POST request, I am getting packagestring value as "2:temp temp temp"
Now, I want to jump to package.php with user firendly url and thats why I created a slug function that convert packagestring to 2-temp-temp-temp and location will be as package.php
htaccess file code is:
RewriteEngine On
RewriteRule ^(.+)/(admin|css|fonts|ico|include|js|images)/(.*)$ $1
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^package/([a-zA-Z0-9-/]+)$ package.php?packagestring=$1
RewriteRule ^package/([a-zA-Z-0-9-]+)/ package.php?packagestring=$1
RewriteRule ^xyz/(css|js|img)/(.*)?$ /$1 [L,QSA,R=301]
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^book_package/([a-zA-Z0-9-/]+)$ book_package.php?booknow=$1
RewriteRule ^book_package/([a-zA-Z-0-9-]+)/ book_package.php?booknow=$1
RewriteRule ^xyz/(css|js|img)/(.*)?$ /$1 [L,QSA,R=301]
Above code will help me to make userfriendly url as
localhost://xyz/package/2-temp-temp-temp
instead of localhost://xyz/package.php?packagestring=2:temp temp temp
by getting the packagestring in package.php file as:
if(!isset($_GET["packagestring"])){
header('location:index.php');
}elseif (isset($_GET["packagestring"])) {
$getpackage = $_GET["packagestring"];
}
Its fine upto here means package.php page Now, I want to jump to book_package.php and below is the package.php POST code when i click on package book button:
function php_slug($string)
{
list($packageid, $packagename) = explode(":",$string);
$url = $packageid."/".strtolower(str_replace(' ', '-', $packagename));
$slug = preg_replace('/[^a-z0-9-]+/', '-', trim(strtolower($url)));
return $url;
}
if(isset($_POST["booknow"])){
$retvalue=$_POST["booknow"];
var_dump($retvalue);
header("location:book_package.php");
}
and below is the book_package code to get the string value :
if(!isset($_GET["booknow"])){
header('location:index.php');
}elseif (isset($_GET["booknow"])) {
$getpackage = $_GET["booknow"];
var_dump($getpackage);
}
This time the requested file is book_package and the htaccess code is mentioned on the above..
Here I am not able to get as well as jump to book_package.php page
I am on the same page (package.php) but with new url as:
http://localhost/xyz/package/2/book_package.php
Here I want
http://localhost/xyz/book_package/2/temp-temp-temp
I think this is okay

Blank Page After Submitting Form in Laravel

I want to add a record to my DB using Laravel but after submitting a form I get a blank screen and no logs. Here's my code:
public function store(Request $request)
{
foreach(Auth::user()->test as $data) {
if($request->name == $data->name) {
return back()->with('wrong', trans('settings.isset.name'));
}
else {
$this->validate($request, [
'name' => 'required',
]);
$name = Name::store($request);
return back()->with('message', trans('settings.add.name'));
}
}
}
And there is, of course, a normal working form. Before when I didn't have foreach it was working, but not it isn't.
I think that this can be caused when Auth::user()->test is empty.
Therefore code inside the foreach loop is not executed and nothing is returned.
You could try putting the return statement to the end of function.
I hope this will do the job
public function store(Request $request)
{
$error = false;
$errors = [];
foreach(Auth::user()->test as $data) {
if($request->name == $data->name) {
$error = true;
$errors['wrong'] = trans('settings.isset.name');
break;
}
else {
$this->validate($request, [
'name' => 'required',
]);
$name = Name::store($request);
}
}
if($error)
return back()->with($errors);
return back()->with('message', trans('settings.add.name'));
}
Use this below .htaccess
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
Options -MultiViews
DirectoryIndex index.php
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteBase /
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^ index.php [L]
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
Give a try to method="POST".

getting 404 not found on server

I'm getting a 404 error on the server, when try load any page. The home page is loaded without problems, on localhost all works fine.
My route class:
static function start()
{
$controller_name = 'add_task';
$action_name = 'index';
$routes = explode('/', $_SERVER['REQUEST_URI']);
if ( !empty($routes[1]) )
{
$controller_name = $routes[1];
}
if ( !empty($routes[2]) )
{
$action_name = $routes[2];
}
$model_name = 'Model_'.$controller_name;
$controller_name = 'Controller_'.$controller_name;
$action_name = 'action_'.$action_name;
$model_file = strtolower($model_name).'.php';
$model_path = "application/models/".$model_file;
if(file_exists($model_path))
{
include "application/models/".$model_file;
}
$controller_file = strtolower($controller_name).'.php';
$controller_path = "application/controllers/".$controller_file;
if(file_exists($controller_path))
{
include "application/controllers/".$controller_file;
}
else
{
Route::ErrorPage404();
}
$controller = new $controller_name;
$action = $action_name;
if(method_exists($controller, $action))
{
$controller->$action();
}
else
{
Route::ErrorPage404();
}
}
function ErrorPage404()
{
...
}
}
My .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]
I can not understand where the problem
Solved my problem by using this htaaccess:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Change value in url than redirect with .htaccess

we have a Wordpress 4.x website with some plugin that verify the availability of rooms. Now we have an url like this:
http://www.pluto.com/en/check-availability/?lang=en&param1=val1&param2=value2&param3=value3&param4=838&param5=value5&param6=value6
We want to change param4=838 with param4=631 than redirect to the new page:
http://www.pluto.com/en/check-availability/?lang=en&param1=val1&param2=value2&param3=value3&param4=631&param5=value5&param6=value6
We want to do this with .htaccess. How can we do that?
Place this rule just below RewriteEngine On line:
RewriteEngine On
RewriteCond %{THE_REQUEST} \?(.*&)?param4=838(&\S*)?\sHTTP [NC]
RewriteRule ^en/check-availability/?$ %{REQUEST_URI}?%1param4=631%2 [R=302,NE,L]
The following permalink rewrite code should be included in your .htaccess file
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
And if you want to be passing arguments in url. Take this example and kindly go through the below link completely
add_filter( 'rewrite_rules_array','my_insert_rewrite_rules' );
add_filter( 'query_vars','my_insert_query_vars' );
add_action( 'wp_loaded','my_flush_rules' );
// flush_rules() if our rules are not yet included
function my_flush_rules(){
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(project)/(\d*)$'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
// Adding a new rule
function my_insert_rewrite_rules( $rules )
{
$newrules = array();
$newrules['(project)/(\d*)$'] = 'index.php pagename=$matches[1]&id=$matches[2]';
return $newrules + $rules;
}
// Adding the id var so that WP recognizes it
function my_insert_query_vars( $vars )
{
array_push($vars, 'id');
return $vars;
}
link here

Categories