Accessing custom scripts via the web. As part of Magento 2 the default web server templates are more secure than the Magento 1 counter parts. For this reason you can't simply add a PHP file to the public directory and call it in your browser.
This guide will show you how to update your webserver configuration (in this case for NGINX) to allow you to call your script in your browser. It must be noted though, that any script you add is a potential security flaw and doing so is at your own risk.
For this example we are going to be adding the following script to an example site, under the url https://www.example.com/my_super_secret_script.php
<?php
phpinfo();
All this will do is printout the PHP info for the current server.
If you are using MDOQ manged Magento hosting please carry out this activity on an instance before taking live.
Guide
- Create your script in the public directory, the name of the file is important as it is what we will use to call the script. In this example I will make the file `public/my_super_secret_script.php`
- Add your desire content to the script
- Validate you can't currently access the script. (Just append the scripts file name to your base url)
- Locate your NGINX configuration.
If you are using MDOQ this will be: `mdoq/nginx/templates/default_site.conf`
If you're not using MDOQ, this could be `/etc/nginx/conf.d/site.conf` or `/etc/nginx/sites-enabled/site.conf` (if unsure your hosting provider should be able to let you know)
You are then looking for the line:
# PHP entry point for main application location ~ (index|get|static|report|404|503|elastic|suggest|health_check)\.php${
- We then need to add to this line to include our new script, you need to take the file name excluding the ".php" and add it to the regex. In this case it would be:
# PHP entry point for main application location ~ (index|get|static|report|404|503|elastic|suggest|health_check|my_super_secret_script)\.php${
- Save the file and reload NGINX
If you are using MDOQ, you can simply "Sync" the NGINX component. (Instance > Sync > Select Nginx > Sync)
If you aren't using MDOQ, this will be something like: `/etc/init.d/nginx configtest && /etc/init.d/nginx reload` - Once happy take your changes live.
If you are on MDOQ, commit your changes to source control (NGINX template file as well as your script), follow the "Im done" process, then sync the production NGINX component.
If your not on MDOQ, you will need to follow your SOP for infrastructure updates.
Extra Tips
- Make sure your file is secure, a good way to do this is to make the file name random. For example use a password generator (just alphanumerics) to generate the file name.
- If you're on MDOQ you can store the url under custom urls, so it doesn't matter how long/obscure the url is. (Settings > Custom URLs) This url will then show up under "links" for your production instance.