Mervyn Lee
Mervyn Lee

Reputation: 2187

Beautify URL on Google App Engine PHP Static Website

I am developing a static website for my friend with some light vanilla PHP code. There is a .php on the url on every page such as xxxxx.com/service.php. I did some research and found out that tweaking on app.yaml is not an elagance method as it will not handling error 404 gracefully. What is in my mind is that I can create a special PHP file taking in request that end with .php from app.yaml and process each request like .htaccess. Due to my lacking of PHP knowledge, I am not able to produce the code in the file. Please enlighten me on the process.

Below is my app.yaml

runtime: php55
api_version: 1
instance_class: F1
automatic_scaling:
  max_idle_instances: 1
  min_pending_latency: 30ms
  max_instances: 1

handlers:
- url: /css
  static_dir: css
  secure: always

- url: /js
  static_dir: js
  secure: always

- url: /images
  static_dir: images
  secure: always

- url: /fonts
  static_dir: fonts
  secure: always

- url: /sitemap\.xml
  static_files: sitemap.xml
  upload: sitemap.xml
  secure: always

- url: /
  script: index.php
  secure: always

- url: /(.+\.php)$
  script: \1
  secure: always

- url: /.*
  script: 404.php
  secure: always

Upvotes: 1

Views: 73

Answers (1)

GAEfan
GAEfan

Reputation: 11360

If you are sure all your static files are already handled in app.yaml, and root (/) is handled, that means anything left would go to a script. So, your final handler could be:

- url: /(.+)
  script: \1.php

I would leave the

- url: /(.+\.php)$
  script: \1

handler above it, as the penultimate handler, so a person can go to /about or /about.php and it will handle both.

- url: /(.+)\.php$
  script: \1.php

Perhaps redirect the .php version to beautified, so users adapt over time without getting a 404:

- url: /(.+)\.php$
  script: redirect.php

redirect.php:

<?php

    require_once __DIR__ . '/../vendor/autoload.php';

    $app = new Silex\Application();

    $app->get('/{scriptName}.php', function($scriptName) {
        header('Location: https://www.example.com/NewAbout/{$scriptName}');
        exit();
    })

?>

Update: To handle 404s, you need a list (like you would in .htaccess) of valid URLs to catch. You can do this using regex in app.yaml. Then, to handle 404s, you finish with a catchall handler:

- url: /(home|about|contact|page1|page99|etc)$ ## the pipe (|) means "or"
  script: \1.php


- url: /.*
  script: 404.php

Then you write a simple 404.php script page to display the proper message and deliver a 404 http response.

Upvotes: 1

Related Questions