CakePHP - Selective SSL - php

How do I force HTTPS for certain parts of a site, e.g. a login page or register page, and use HTTP for the rest of the site?

My favorite convert to https forcing method is to put this as the first thing in your php script. It works in Joomla, and may very well work in CakePHP.
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/'.basename($_SERVER['PHP_SELF']));
die();
}
This snippet will force https on whatever page you are viewing. If you want to isolate certian pages, just put some conditions based on the information in the "$_SERVER['PHP_SELF']" variable.
Otherwise, modify the .htaccess file, assuming your host allows you access to this:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} somefolder
RewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]

I did the exact thing with CodeIgniter. I'm not totally familiar with CakePHP but I'm sure the process is similar.
I setup apache to point SSL and non-SSL traffic to the same directory.
Then I created an array in the config that listed which controllers needed to have SSL (register, login, etc)
Then created a function in an autoloaded helper that checked to see if the current controller was in that array and then it would reset the base_url with https:// instead of http://. If the controller wasn't in the array, it would force the base_url to http://.
Worked flawlessly for me. Let me know if code examples from my CodeIgniter project would be helpful.
Similar post that may help.

You may load the RequestHandler component and use the isSsl() function to determine if it is coming from a http or https, if !isSsl then redirect it to a https page :) else do whatever other thing you want.
book info of the isSsl function here

A better solution might be doing this with mod_rewrite with htaccess for certain Url's and leaving the code out of it all together.
You can setup your rewrite rules for just certain Url's.
Here is a lead on how to do it for an entire site:
http://www.besthostratings.com/articles/force-ssl-htaccess.html

Related

WordPress: can't achieve direct image access redirection via .htaccess

My goal is the following: when a user tries to access an image (or any other attachments in /wp-content/uploads/) I need to redirect him to a processor PHP file that will check if a user is logged in and the file is uploaded by that user.
I've come to this solution so far:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^.*wp-content/uploads/.*
RewriteRule ^wp-content/uploads/(.*)$ file-processor.php?file=$1 [QSA,L]
</IfModule>
And it just doesn't work. 😒 I've tried a huge amount of different combinations and had no luck. And then I've decided to try something simpler and found out that I can't even redirect directly accessed images via the following code (while it works fine for any other pages of the website):
Redirect 301 / https://example.com/
And that's part is really confusing... Should there be some different treatment to the files that are accessed directly?
To make it clear. With the last code I got the following behaviour:
If I try to access any page on the website (ex.: "siteurl.com" or "siteurl.com/about"), then I get redirection to "https://example.com/" as expected.
If I try to access media "siteurl.com/wp-content/uploads/2021/10/someimg.jpg", then I can access this media and see it, while I still expect to be redirected to "https://example.com", but I don't get any redirection.
The same problem happens with directly accessed files from my theme. I still can access them despite this last redirect rule in .htaccess:
Redirect 301 / https://example.com/
Could you please explain how to redirect directly accessed files then?
Thanks in advance! 😁
It sounds like you may be behind a front-end-proxy that is intended to serve your static content. (Nginx is commonly used for this.) The proxy serves the static content, completely bypassing your application server (Apache / .htaccess). This provides great performance at the expense of some functionality.
Check the HTTP response headers when requesting one of these images. You may get a clue as to what is happening by checking the Server HTTP response header.
Possible solutions would be to either:
Make an exception in the front-end proxy to exclude the /wp-content/uploads directory.
OR
Reference these images/resources by a different URL to the actual filesystem path.
Since you are wanting to "protect" these resources you would need to store them outside of the public HTML space (ie. above the document root) - so they are not accessible via the proxy. You can then use the same URL (ie. /wp-content/uploads/...) if you wish, but the script (file-processor.php) would read the file from this alternative location.

How do I use PHP with SSL

My server provides SSL connections via https, although the certificate costs extra...
Is there anything that needs to be changed in the PHP code to utilize this protocol?
My site has:
ajax forms via POST
regular forms and pages using POST and GET parameters
Session variables
You should be good to go. PHP does not impact the use of SSL or not.
Things you should check are:
Are all URLS in you application relative (no http://)
Are assets (CSS/JS/IMG) used in your site (both from internal and external sources) also as relative paths or prefixed with https://
Having an asset without https:// in a SSL powered site, the browsers will warn you visitors that something ain't right.
you can use the server .htaccess file to redirect all your links. So when the standard page is opened via say a link the server redirects to the https version...
# Permanent reirect ALL old pages to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Other than any hard-coded URLs, no, your code shouldn't know about the difference, nor care.
I'd have to say the same as mvbrakel, but as far as session cookies/cookies you will want to turn on HTTPS only if you are using https on ALL your pages.
Also adding HTTP only to cookies, js scripts won't be able to check value and such.
The code does not need to be changed, other than to change all links from http:// to https:// (seriously, don't forget that, else you aren't using SSL...)

301 redirect in .htaccess for 30,000 errors

I've been tasked to clean up 30,000 or so url errors left behind from an old website as the result of a redesign and development.
I normally use .htaccess to do this, but I doubt it would be wise to have 30,000 301 redirects inside the .htaccess file!
What methods have some of you used to solve this problem?
Thanks in advance.
Here as you can do with apache httpd
RewriteMap escape int:escape
RewriteMap lowercase int:tolower
RewriteMap my_redir_map txt:map_rewrite.txt
RewriteCond ${my_redir_map:${lowercase:${escape:%{HTTP_HOST}%{REQUEST_URI}}}} ^(.+)$
RewriteRule .* http://%1 [R=301,L]
I use this rewrite rules usually directly inside apache httpd configuration.
Inside the map_rewrite.txt file you have a tab delimited file with the list of redirect in the following format:
www.example.it/tag/nozze www.example.it/categoria/matrimonio
www.example.it/tag/pippo www.example.it/pluto
www.example.it/tag/ancora www.google.com
Would be much easier if you can generalize the approach because the redirect have a common pattern. But if not, in this case you only need to add the redirected url into the list.
Take care to study the RewriteMap configuration, because you can also write the list into a different format, for example like a database table.
Please pay attention to this: I have added escape and lowercase only because there are accents into the urls I need to write. If your urls doesn't have accents, you can remove both.
If you want implement these redirects in php, here the code you need:
<?php
$dest_url = "http://example.com/path...";
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$dest_url);
Create a PHP page to operate as a 404 handler. It should inspect the incoming URL, check if it should map from an old page to a new page, then issue a 301. If there is no mapping then present a 404.
Simply set this page as the 404 handler in your .htaccess and there you go. IIRC this is how Wordpress used to handle 'clean' URLs on IIS before IIS7 brought in URL rewriting without needing a 3rd-party dll.
I have made a redirect class that is on the 404 page that will check the database if there is a valid page to 301 redirect to and redirect it instead of giving the 404 page. If it can't figure that out, it marks it in the database as a 404 page, so it can be fixed later.
Thanks for help guys. I've carried out the suggested course of action from freedev but have created a separate config file within Apache.
Within the httpd.conf file I have added:
# Map settings
Include "conf/extra/map.conf"
The map.conf file:
RewriteEngine On
RewriteEngine on
RewriteMap url_rewrite_map txt:conf/map.map
RewriteCond ${url_rewrite_map:$1|NOT_FOUND} !NOT_FOUND
RewriteRule ^(.*) http://website.com/${url_rewrite_map:$1} [R=301]
The map.map file is formatted as:
/oldname/ /newname
I've added quite a few of the urls for the redirection and so far so good, it isn't having a massive impact on the server like it did when added to .htaccess

redirect facebook app to canvas url if host url is hit directly

I have iframe based facebook app, I just want to do is that whenever someone hits the application url directly http://mysite.com must be redirect to my facebook canvas url for this app say http://apps.facebook.com/mysite. This seems pretty easy but unfortunately its not clicking in my mind
any help would be appreciated
EDIT
the application is in codeigniter
EDIT
htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
php_value error_reporting 7
php_flag display_errors On
php_value auto_prepend_file prepend.php
say my domain is
http://abc.com/mysitefolder
my facebook app link is
http://apps.facebook.com/myappname
please consider http and https conversion too
also guyz one suggestion too as you see am using prepend in htaccess its just to get the user timezone for some date time stuff, is this fine am using it this way? the file actually sets a cookie for a user on very first visit to the site per session
Best Regards
Junaid
Any canvas page for an app that comes from Facebook will have $_REQUEST['signed_request'] defined. You could check for the existence of this request variable and if it is not set, redirect to Facebook.
well as far as i know there isn't any server side coding to do so... then again how could there be since it's all happening on the frontside of things what you could do is using javascript like so
if(window!=window.top){i am iframed now redirect or w/e you wanna do}
Since you want to redirect the domain name to the app, not the other way around, the fact that the app is in an iFrame isn't relevant.
The best way to do it is using .htaccess, in my opinion. This means that you can use custom URLs such as mydomainname.com/mypagename/, which would redirect to apps.facebook.com/myappname/mypagename/, so you can advertise your app easier. Another benefit is that you don't have to rely on Javascript. Some people (very small amount) have it turned off, but why parse all the PHP code to do it?
So, what you can do is have the root domain "blank" and only include the following in your .htaccess file:
RewriteEngine on
RewriteRule ^$ http://www.mydomainname.com/ [R=301,L,QSA]
RewriteRule ^/(.*) http://www.mydomainname.com/$1 [R=301,L,QSA]
QSA will also attach query parameters to the destination URL, such as "?ref=email".
Of course, if you keep the app code on the same domain, in the root, you don't really need to do anything, just tweak your authentification code.
If this doesn't work for you, please give us more details:
Where does the app "live"
If the app sits in the mydomainname.com, what happens when you access the URL directly?
How do you do the authentification?
Code helps, obviously.
Unless mydomainname.com isn't specific for the app, I'd recommend hosting the actual app on a subdomain. Actually, regardless, should help you organize. Or you might want to make the app accesibile as a website as well, with a Facebook login option.
Cheers

How to setup .htaccess to show 404 for unallowed urls?

I noticed in Drupal if you add .php to the url bar of any page it gives you a 404 message; clean urls enabled. The page is obviously a .php, but the .htaccess is preventing the user from being able to tamper with url extensions in the url bar. How could you do this using .htaccess. I have file extensions omitted at the moment, but would also like to add that feature. Thank you.
Also, this question does not pertain to Drupal. I only mentioned Drupal for and example.
Just because a file contains PHP code it doesn't mean it has to have the .php extension; even more so when you're accessing a file over the internet.
When you request http://mysite.com/page and you're using an .htaccess like Drupal's, the request is forwarded onto index.php?q=page whereupon Drupal will check it's database for a path matching page. If it finds one it will display the content for that page, if not it will (rightly) give a 404.
If you want all of your pages to be accessible with a PHP extension you could add an extra rule in your .htaccess file to remove .php from any request where the PHP file doesn't physically exist:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.php $1 [NC]
Bear in mind though that this adds zero extra value for your site's visitors (in fact they have to remember a file extension as well as the path to the page), and it exposes exactly what server-side technology you're using so a potential attacker would have some of his work done for him.
Hope that helps.
Could you please explain that in more depth. How can it redirect content into an existing page? Is that common practice / typical way of doing things?
Yes it is a very common practice, used by most frameworks and CMS.
The principle is simple: you setup your .htaccess so that every request which doesn't match a real file or directory will be redirected to a front controller, usually the index.php in the root directory of the application. That front controller handles the request by analyzing the URL and calling the necessary actions.
In this way you can minimize the rewrite rules to just one, and you can offer customized 404 pages.
I dunno Drupal but in the usual php app every request being routed to the front controller which performs some validations and throws 404 on errors.
easy-peasy

Categories